Skip to main content

moq_ext_egui/
pending.rs

1//! A task whose one result a window collects on a later frame.
2
3use std::task::Poll;
4
5use n0_future::task::{AbortOnDropHandle, spawn};
6use tokio::sync::oneshot;
7
8/// A task whose one result a window collects on a later frame.
9///
10/// An egui window cannot await. It starts work such as a dial or a device
11/// open with [`spawn`](Self::spawn), and asks [`poll`](Self::poll) on each
12/// frame until the result is there. The task repaints the window when it
13/// finishes, so the window draws the result at once. Dropping the handle
14/// aborts the task.
15///
16/// # Examples
17///
18/// ```no_run
19/// use std::task::Poll;
20///
21/// use moq_ext_egui::Pending;
22///
23/// # fn update(ctx: &egui::Context, pending: &mut Option<Pending<u32>>) {
24/// let task = pending.get_or_insert_with(|| Pending::spawn(ctx, async { 42 }));
25/// if let Poll::Ready(result) = task.poll() {
26///     println!("finished with {result:?}");
27///     *pending = None;
28/// }
29/// # }
30/// ```
31#[derive(Debug)]
32pub struct Pending<T> {
33    rx: oneshot::Receiver<T>,
34    task: AbortOnDropHandle<()>,
35}
36
37impl<T: Send + 'static> Pending<T> {
38    /// Runs `future` in a task and repaints `ctx` when it finishes.
39    ///
40    /// A result that arrives after [`cancel`](Self::cancel) or a drop is
41    /// dropped.
42    ///
43    /// # Panics
44    ///
45    /// Panics when called outside a Tokio runtime.
46    #[must_use]
47    pub fn spawn(ctx: &egui::Context, future: impl Future<Output = T> + Send + 'static) -> Self {
48        Self::spawn_with_late(ctx, future, drop)
49    }
50
51    /// Runs `future` in a task, and hands a result nobody waits for any more to `late`.
52    ///
53    /// For a result that holds something to close, such as a session that
54    /// connected after the window gave up on it. The task can only finish
55    /// late after [`cancel`](Self::cancel), since a drop aborts it.
56    ///
57    /// # Panics
58    ///
59    /// Panics when called outside a Tokio runtime.
60    #[must_use]
61    pub fn spawn_with_late(
62        ctx: &egui::Context,
63        future: impl Future<Output = T> + Send + 'static,
64        late: impl FnOnce(T) + Send + 'static,
65    ) -> Self {
66        let (tx, rx) = oneshot::channel();
67        let ctx = ctx.clone();
68        let task = spawn(async move {
69            if let Err(result) = tx.send(future.await) {
70                late(result);
71            }
72            ctx.request_repaint();
73        });
74        Self {
75            rx,
76            task: AbortOnDropHandle::new(task),
77        }
78    }
79
80    /// Returns the result once the task has finished.
81    ///
82    /// Returns `Ready(None)` for a task that stopped without a result, which
83    /// happens after [`cancel`](Self::cancel), and while the runtime shuts
84    /// down.
85    pub fn poll(&mut self) -> Poll<Option<T>> {
86        match self.rx.try_recv() {
87            Ok(result) => Poll::Ready(Some(result)),
88            Err(oneshot::error::TryRecvError::Empty) => Poll::Pending,
89            Err(oneshot::error::TryRecvError::Closed) => Poll::Ready(None),
90        }
91    }
92
93    /// Stops the task and returns a result it delivered before it stopped.
94    pub fn cancel(&mut self) -> Option<T> {
95        self.rx.close();
96        self.task.abort();
97        self.rx.try_recv().ok()
98    }
99
100    /// Waits for the result, keeping the task alive until it is there.
101    ///
102    /// For a task that another task takes over, such as a connection start
103    /// that a restart must wait for and close before it starts again, where
104    /// [`cancel`](Self::cancel) would drop the result unclosed. Returns `None`
105    /// for a task that stopped without a result, as [`poll`](Self::poll) does.
106    ///
107    /// Cancel safe: dropping the future aborts the task, as dropping the
108    /// handle does.
109    pub async fn wait(self) -> Option<T> {
110        let Self { rx, task } = self;
111        let result = rx.await.ok();
112        drop(task);
113        result
114    }
115}
116
117#[cfg(test)]
118mod tests {
119    use std::time::Duration;
120
121    use super::*;
122
123    /// Polls `pending` until it is ready, failing after a second.
124    async fn ready<T: Send + 'static>(pending: &mut Pending<T>) -> Option<T> {
125        tokio::time::timeout(Duration::from_secs(1), async {
126            loop {
127                if let Poll::Ready(result) = pending.poll() {
128                    return result;
129                }
130                tokio::time::sleep(Duration::from_millis(5)).await;
131            }
132        })
133        .await
134        .expect("the task finished")
135    }
136
137    #[tokio::test]
138    async fn a_finished_task_hands_over_its_result() {
139        let ctx = egui::Context::default();
140        let mut pending = Pending::spawn(&ctx, async { 7 });
141        assert_eq!(ready(&mut pending).await, Some(7));
142    }
143
144    /// A task awaited elsewhere, here from another task, hands its result over.
145    #[tokio::test]
146    async fn a_waited_task_hands_over_its_result() {
147        let ctx = egui::Context::default();
148        let (go_tx, go_rx) = oneshot::channel();
149        let pending = Pending::spawn(&ctx, async move { go_rx.await.expect("sent") });
150        let waiter = tokio::spawn(pending.wait());
151        go_tx.send(9).expect("the task waits");
152        let result = tokio::time::timeout(Duration::from_secs(1), waiter)
153            .await
154            .expect("the task finished")
155            .expect("the waiter ran");
156        assert_eq!(result, Some(9));
157    }
158
159    /// A cancelled task delivers nothing, and reads as ended.
160    #[tokio::test]
161    async fn a_cancelled_task_reads_as_ended() {
162        let ctx = egui::Context::default();
163        let mut pending = Pending::spawn(&ctx, std::future::pending::<u32>());
164        assert_eq!(pending.poll(), Poll::Pending);
165        assert_eq!(pending.cancel(), None);
166        assert_eq!(pending.poll(), Poll::Ready(None));
167    }
168}