diff options
author | 2022-01-14 19:55:27 +0700 | |
---|---|---|
committer | 2022-01-14 19:55:27 +0700 | |
commit | 2a3271dc106b702a6b81888506578ec5f845281b (patch) | |
tree | de4e495404bf9e89f8256cb7a067e3c125b39e0d /native | |
parent | 7442d0b66f1c7b4c912ad5ac358dafcc8b07824e (diff) | |
download | iced-2a3271dc106b702a6b81888506578ec5f845281b.tar.gz iced-2a3271dc106b702a6b81888506578ec5f845281b.tar.bz2 iced-2a3271dc106b702a6b81888506578ec5f845281b.zip |
Implement `subscription::unfold` :tada:
Diffstat (limited to 'native')
-rw-r--r-- | native/src/subscription.rs | 23 |
1 files changed, 22 insertions, 1 deletions
diff --git a/native/src/subscription.rs b/native/src/subscription.rs index 420797d1..9ff89ccf 100644 --- a/native/src/subscription.rs +++ b/native/src/subscription.rs @@ -2,7 +2,8 @@ use crate::event::{self, Event}; use crate::Hasher; -use iced_futures::futures::{self, Stream}; +use iced_futures::futures::channel::mpsc; +use iced_futures::futures::{self, Future, Stream}; use iced_futures::BoxStream; use std::hash::Hash; @@ -103,6 +104,26 @@ where }) } +/// Returns a [`Subscription`] that will create and asynchronously run a +/// [`Stream`] that will call the provided closure to produce every `Message`. +/// +/// The `initial` state will be used to uniquely identify the [`Subscription`]. +pub fn unfold<T, Fut, Message>( + initial: T, + mut f: impl FnMut(T) -> Fut + Send + Sync + 'static, +) -> Subscription<Message> +where + Message: 'static, + T: Clone + Hash + Send + 'static, + Fut: Future<Output = (Message, T)> + Send + 'static, +{ + use futures::future::FutureExt; + + run(initial, move |initial| { + futures::stream::unfold(initial, move |state| f(state).map(Some)) + }) +} + struct Runner<T, F, S, Message> where F: FnOnce(T, EventStream) -> S, |