File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff 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+ }
You can’t perform that action at this time.
0 commit comments