From 9ea79259d5f8b6ad53c1e7a99b285a072e2a7b2c Mon Sep 17 00:00:00 2001 From: Antonio Scandurra Date: Thu, 26 Oct 2023 15:00:44 +0200 Subject: [PATCH] Add spawn facilities to `AsyncWindowContext` --- crates/gpui2/src/app/async_context.rs | 35 +++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/crates/gpui2/src/app/async_context.rs b/crates/gpui2/src/app/async_context.rs index 308e51908933e69707633feea685e7e3c75f5a68..ab42a56cbb22a2eac2ba16f7bafee25a0be035fd 100644 --- a/crates/gpui2/src/app/async_context.rs +++ b/crates/gpui2/src/app/async_context.rs @@ -183,6 +183,41 @@ impl AsyncWindowContext { self.app .update_window(self.window, |cx| cx.update_global(update)) } + + pub fn spawn( + &self, + f: impl FnOnce(AsyncWindowContext) -> Fut + Send + 'static, + ) -> Task + where + Fut: Future + Send + 'static, + R: Send + 'static, + { + let this = self.clone(); + self.executor.spawn(async move { f(this).await }) + } + + pub fn spawn_on_main( + &self, + f: impl FnOnce(AsyncWindowContext) -> Fut + Send + 'static, + ) -> Task + where + Fut: Future + 'static, + R: Send + 'static, + { + let this = self.clone(); + self.executor.spawn_on_main(|| f(this)) + } + + pub fn run_on_main( + &self, + f: impl FnOnce(&mut MainThread) -> R + Send + 'static, + ) -> Task> + where + R: Send + 'static, + { + self.update(|cx| cx.run_on_main(f)) + .unwrap_or_else(|error| Task::ready(Err(error))) + } } impl Context for AsyncWindowContext {