Skip to main content

iced_futures/backend/native/
smol.rs

1//! A `smol` backend.
2
3/// A `smol` executor.
4#[derive(Debug)]
5pub struct Executor;
6
7impl crate::Executor for Executor {
8    fn new() -> Result<Self, futures::io::Error> {
9        Ok(Self)
10    }
11
12    fn spawn(&self, future: impl Future<Output = ()> + Send + 'static) {
13        smol::spawn(future).detach();
14    }
15
16    fn block_on<T>(&self, future: impl Future<Output = T>) -> T {
17        smol::block_on(future)
18    }
19}
20
21pub mod time {
22    //! Listen and react to time.
23    use crate::MaybeSend;
24    use crate::core::time::{Duration, Instant};
25    use crate::subscription::Subscription;
26
27    use futures::stream;
28
29    /// Returns a [`Subscription`] that produces messages at a set interval.
30    ///
31    /// The first message is produced after a `duration`, and then continues to
32    /// produce more messages every `duration` after that.
33    pub fn every(duration: Duration) -> Subscription<Instant> {
34        Subscription::run_with(duration, |duration| {
35            use futures::stream::StreamExt;
36
37            let start = Instant::now() + *duration;
38
39            smol::Timer::interval_at(start, *duration).boxed()
40        })
41    }
42
43    /// Returns a [`Subscription`] that runs the given async function at a
44    /// set interval; producing the result of the function as output.
45    pub fn repeat<F, T>(f: fn() -> F, interval: Duration) -> Subscription<T>
46    where
47        F: Future<Output = T> + MaybeSend + 'static,
48        T: MaybeSend + 'static,
49    {
50        Subscription::run_with((f, interval), |(f, interval)| {
51            let f = *f;
52            let interval = *interval;
53
54            stream::unfold(0, move |i| async move {
55                if i > 0 {
56                    _ = smol::Timer::after(interval).await;
57                }
58
59                Some((f().await, i + 1))
60            })
61        })
62    }
63}