cosmic/executor/
single.rs

1// Copyright 2023 System76 <info@system76.com>
2// SPDX-License-Identifier: MPL-2.0
3
4//! An async executor that schedules tasks on the same background thread.
5
6use std::future::Future;
7
8#[cfg(feature = "tokio")]
9pub struct Executor(tokio::runtime::Runtime);
10
11#[cfg(feature = "tokio")]
12impl iced::Executor for Executor {
13    fn new() -> Result<Self, iced::futures::io::Error> {
14        // Current thread executor requires calling `block_on` to actually run
15        // futures. Main thread is busy with things other than running futures,
16        // so spawn a single worker thread.
17        Ok(Self(
18            tokio::runtime::Builder::new_multi_thread()
19                .worker_threads(1)
20                .enable_all()
21                .build()?,
22        ))
23    }
24
25    fn spawn(&self, future: impl Future<Output = ()> + Send + 'static) {
26        let _res = self.0.spawn(future);
27    }
28
29    fn enter<R>(&self, f: impl FnOnce() -> R) -> R {
30        let _guard = self.0.enter();
31        f()
32    }
33}