pub struct AsyncReducer<Data: AsyncReducible> { /* private fields */ }Expand description
A type that allows you to share information across your application easily with async operations.
Async reducers receive messages, update their state asynchronously, and notify their subscribers.
Unlike SharedState, this type doesn’t
allow direct access to the internal data.
Instead, it updates its state after receiving messages, similar to components.
After the message is processed, all subscribers will be notified.
This is the async variant of Reducer, where the
reduce method can perform asynchronous operations.
§Example
use relm4::{AsyncReducer, AsyncReducible};
struct CounterReducer(u8);
enum CounterInput {
Increment,
Decrement,
}
impl AsyncReducible for CounterReducer {
type Input = CounterInput;
async fn init() -> Self {
Self(0)
}
async fn reduce(&mut self, input: Self::Input) -> bool {
match input {
CounterInput::Increment => {
self.0 += 1;
}
CounterInput::Decrement => {
self.0 -= 1;
}
}
true
}
}
// Create the reducer.
static REDUCER: AsyncReducer<CounterReducer> = AsyncReducer::new();
// Update the reducer.
REDUCER.emit(CounterInput::Increment);
// Create a channel and subscribe to changes.
let (sender, receiver) = relm4::channel();
REDUCER.subscribe(&sender, |data| data.0);
// Count up to 2.
REDUCER.emit(CounterInput::Increment);
assert_eq!(receiver.recv_sync().unwrap(), 2);Implementations§
Source§impl<Data> AsyncReducer<Data>where
Data: AsyncReducible + 'static,
impl<Data> AsyncReducer<Data>where
Data: AsyncReducible + 'static,
Sourcepub const fn new() -> Self
pub const fn new() -> Self
Create a new AsyncReducer variable.
The data will be initialized lazily on the first access.
Sourcepub fn subscribe<Msg, F>(&self, sender: &Sender<Msg>, f: F)
pub fn subscribe<Msg, F>(&self, sender: &Sender<Msg>, f: F)
Subscribe to an AsyncReducer.
Any subscriber will be notified with a message every time
you modify the reducer (by calling Self::emit()).
Sourcepub fn subscribe_optional<Msg, F>(&self, sender: &Sender<Msg>, f: F)
pub fn subscribe_optional<Msg, F>(&self, sender: &Sender<Msg>, f: F)
An alternative version of subscribe() that only send a message if
the closure returns Some.
Sourcepub fn emit(&self, input: Data::Input)
pub fn emit(&self, input: Data::Input)
Sends a message to the reducer to update its state asynchronously.
If the AsyncReducible::reduce() method returns true,
all subscribers will be notified.