Skip to content

Commit 72b6020

Browse files
authored
feat: Radio::write_with_map_channel (#16)
1 parent ddfc55c commit 72b6020

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

src/hooks/use_radio.rs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -342,6 +342,36 @@ where
342342
let guard = self.write_channel(channel);
343343
cb(guard);
344344
}
345+
346+
/// Get a mutable reference to the current state value, inside a callback that returns the channel to be used.
347+
///
348+
/// Example:
349+
///
350+
/// ```rs
351+
/// radio.write_with_map_channel(|value| {
352+
/// // Modify `value`
353+
/// if value.cool {
354+
/// Channel::Whatever
355+
/// } else {
356+
/// Channel::SomethingElse
357+
/// }
358+
/// });
359+
/// ```
360+
pub fn write_with_map_channel(
361+
&mut self,
362+
cb: impl FnOnce(&mut RadioGuard<Value, Channel>) -> Channel,
363+
) {
364+
let value = self.antenna.peek().station.value.write_unchecked();
365+
let mut guard = RadioGuard {
366+
channels: Vec::default(),
367+
antenna: self.antenna,
368+
value,
369+
};
370+
let channel = cb(&mut guard);
371+
for channel in channel.derive_channel(&guard.value) {
372+
self.antenna.peek().station.notify_listeners(&channel)
373+
}
374+
}
345375
}
346376

347377
/// Consume the state and subscribe using the given `channel`

0 commit comments

Comments
 (0)