seed/app/
stream_manager.rs

1use futures::future::{abortable, ready, AbortHandle, FutureExt};
2use futures::stream::{Stream, StreamExt};
3use wasm_bindgen_futures::spawn_local;
4
5// ------ StreamManager ------
6
7pub(crate) struct StreamManager;
8
9impl StreamManager {
10    pub fn stream(stream: impl Stream<Item = ()> + 'static) {
11        // Convert `Stream` to `Future` and execute it. The stream is "leaked" into the JS world.
12        spawn_local(stream.for_each(|_| ready(())));
13    }
14
15    pub fn stream_with_handle(stream: impl Stream<Item = ()> + 'static) -> StreamHandle {
16        // Convert `Stream` to `Future`.
17        let stream = stream.for_each(|_| ready(()));
18        // Create `AbortHandle`.
19        let (stream, handle) = abortable(stream);
20        // Ignore the error when the future is aborted. I.e. just stop the stream.
21        spawn_local(stream.map(move |_| ()));
22        StreamHandle(handle)
23    }
24}
25
26// ------ StreamHandle ------
27
28#[derive(Debug)]
29pub struct StreamHandle(AbortHandle);
30
31impl Drop for StreamHandle {
32    fn drop(&mut self) {
33        self.0.abort();
34    }
35}