use std::future::Future;
use teksilo_core::{EventContext, TeksiloWindowId};
use crate::executor::{AsyncRuntimeHandle, TaskHandle};
const NOT_INSTALLED: &str = "teksilo-async: AsyncRuntimeHandle not installed — call \
TeksiloAppBuilder::install_async() at startup";
pub trait EventContextAsyncExt {
fn spawn_local(&mut self, future: impl Future<Output = ()> + 'static) -> TaskHandle;
fn spawn_local_with<R: 'static>(
&mut self,
future: impl Future<Output = R> + 'static,
on_complete: impl FnOnce(R, &mut EventContext) + 'static,
) -> TaskHandle;
}
impl EventContextAsyncExt for EventContext<'_> {
fn spawn_local(&mut self, future: impl Future<Output = ()> + 'static) -> TaskHandle {
let handle = self
.app_state::<AsyncRuntimeHandle>()
.expect(NOT_INSTALLED)
.clone();
if let Some(poster) = self.poster() {
handle.set_poster(poster.clone());
}
handle.spawn_local(future)
}
fn spawn_local_with<R: 'static>(
&mut self,
future: impl Future<Output = R> + 'static,
on_complete: impl FnOnce(R, &mut EventContext) + 'static,
) -> TaskHandle {
let handle = self
.app_state::<AsyncRuntimeHandle>()
.expect(NOT_INSTALLED)
.clone();
if let Some(poster) = self.poster() {
handle.set_poster(poster.clone());
}
let window_id: TeksiloWindowId = self
.window()
.map(|w| w.id())
.expect("teksilo-async: spawn_local_with requires a window context");
handle.spawn_local_with(window_id, future, on_complete)
}
}