diff options
author | 2022-01-17 15:48:37 +0700 | |
---|---|---|
committer | 2022-01-17 15:48:37 +0700 | |
commit | 5ce8653fb51c035e0a6fe1ba7ab363018cdf107b (patch) | |
tree | 06ab57aaf4dada3a5b7cef6f331a22c47183ac5e /native | |
parent | ddbbe7353bce0827160cb8d539a3114c159b3745 (diff) | |
download | iced-5ce8653fb51c035e0a6fe1ba7ab363018cdf107b.tar.gz iced-5ce8653fb51c035e0a6fe1ba7ab363018cdf107b.tar.bz2 iced-5ce8653fb51c035e0a6fe1ba7ab363018cdf107b.zip |
Add worker example to docs of `subscription::unfold`
Diffstat (limited to 'native')
-rw-r--r-- | native/src/subscription.rs | 65 |
1 files changed, 65 insertions, 0 deletions
diff --git a/native/src/subscription.rs b/native/src/subscription.rs index ece6556e..63834654 100644 --- a/native/src/subscription.rs +++ b/native/src/subscription.rs @@ -91,6 +91,71 @@ where /// [`Stream`] that will call the provided closure to produce every `Message`. /// /// The `id` will be used to uniquely identify the [`Subscription`]. +/// +/// # Creating an asynchronous worker with bidirectional communication +/// You can leverage this helper to create a [`Subscription`] that spawns +/// an asynchronous worker in the background and establish a channel of +/// communication with an `iced` application. +/// +/// You can achieve this by creating an `mpsc` channel inside the closure +/// and returning the `Sender` as a `Message` for the `Application`: +/// +/// ``` +/// use iced_native::subscription::{self, Subscription}; +/// use iced_native::futures::channel::mpsc; +/// +/// pub enum Event { +/// Ready(mpsc::Sender<Input>), +/// WorkFinished, +/// // ... +/// } +/// +/// enum Input { +/// DoSomeWork, +/// // ... +/// } +/// +/// enum State { +/// Starting, +/// Ready(mpsc::Receiver<Input>), +/// } +/// +/// fn some_worker() -> Subscription<Event> { +/// struct SomeWorker; +/// +/// subscription::unfold(std::any::TypeId::of::<SomeWorker>(), State::Starting, |state| async move { +/// match state { +/// State::Starting => { +/// // Create channel +/// let (sender, receiver) = mpsc::channel(100); +/// +/// (Some(Event::Ready(sender)), State::Ready(receiver)) +/// } +/// State::Ready(mut receiver) => { +/// use iced_native::futures::StreamExt; +/// +/// // Read next input sent from `Application` +/// let input = receiver.select_next_some().await; +/// +/// match input { +/// Input::DoSomeWork => { +/// // Do some async work... +/// +/// // Finally, we can optionally return a message to tell the +/// // `Application` the work is done +/// (Some(Event::WorkFinished), State::Ready(receiver)) +/// } +/// } +/// } +/// } +/// }) +/// } +/// ``` +/// +/// Check out the [`websocket`] example, which showcases this pattern to maintain a WebSocket +/// connection open. +/// +/// [`websocket`]: https://github.com/iced-rs/iced/tree/0.4/examples/websocket pub fn unfold<I, T, Fut, Message>( id: I, initial: T, |