Skip to content

Commit 92c6e35

Browse files
committed
refactor: add map_watcher
Signed-off-by: Gustavo Inacio <[email protected]>
1 parent d89b5b0 commit 92c6e35

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

crates/watcher/src/lib.rs

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,3 +113,34 @@ where
113113
}
114114
})
115115
}
116+
117+
// Maps all outputs of Receiver into a new watcher
118+
pub fn map_watcher<T1, T2, F>(
119+
mut receiver: watch::Receiver<T1>,
120+
map_function: F,
121+
) -> watch::Receiver<T2>
122+
where
123+
T1: Clone + Send + Sync + 'static,
124+
T2: Send + Sync + 'static,
125+
F: Fn(T1) -> T2 + Send + 'static,
126+
{
127+
let initial_value = map_function(receiver.borrow().clone());
128+
let (tx, rx) = watch::channel(initial_value);
129+
130+
tokio::spawn(async move {
131+
loop {
132+
select! {
133+
Ok(())= receiver.changed() =>{},
134+
else=>{
135+
// Something is wrong.
136+
panic!("receiver was dropped");
137+
}
138+
}
139+
140+
let current_val = receiver.borrow().clone();
141+
let mapped_value = map_function(current_val);
142+
tx.send(mapped_value).expect("Failed to update channel");
143+
}
144+
});
145+
rx
146+
}

0 commit comments

Comments
 (0)