use crate::CancellationToken;
use core::future::Future;
#[derive(Debug)]
pub struct FluxionTask {
cancel: CancellationToken,
}
impl FluxionTask {
#[cfg(not(target_arch = "wasm32"))]
pub fn spawn<F, Fut>(f: F) -> Self
where
F: FnOnce(CancellationToken) -> Fut + Send + 'static,
Fut: Future<Output = ()> + Send + 'static,
{
let cancel = CancellationToken::new();
let cancel_clone = cancel.clone();
let _future = f(cancel_clone);
#[cfg(all(
feature = "runtime-tokio",
not(all(feature = "runtime-smol", not(feature = "runtime-tokio"))),
not(all(
feature = "runtime-async-std",
not(feature = "runtime-tokio"),
not(feature = "runtime-smol")
))
))]
tokio::spawn(_future);
#[cfg(all(feature = "runtime-smol", not(feature = "runtime-tokio")))]
smol::spawn(_future).detach();
#[cfg(all(
feature = "runtime-async-std",
not(target_arch = "wasm32"),
not(feature = "runtime-tokio"),
not(feature = "runtime-smol")
))]
async_std::task::spawn(_future);
Self { cancel }
}
#[cfg(target_arch = "wasm32")]
pub fn spawn<F, Fut>(f: F) -> Self
where
F: FnOnce(CancellationToken) -> Fut + 'static,
Fut: Future<Output = ()> + 'static,
{
let cancel = CancellationToken::new();
let cancel_clone = cancel.clone();
let _future = f(cancel_clone);
wasm_bindgen_futures::spawn_local(_future);
Self { cancel }
}
pub fn cancel(&self) {
self.cancel.cancel();
}
pub fn is_cancelled(&self) -> bool {
self.cancel.is_cancelled()
}
}
impl Drop for FluxionTask {
fn drop(&mut self) {
self.cancel.cancel();
}
}