]> git.proxmox.com Git - ui/proxmox-yew-widget-toolkit.git/commitdiff
add async abort guard
authorDietmar Maurer <dietmar@proxmox.com>
Wed, 23 Oct 2024 08:58:54 +0000 (10:58 +0200)
committerDietmar Maurer <dietmar@proxmox.com>
Wed, 23 Oct 2024 09:40:51 +0000 (11:40 +0200)
Signed-off-by: Dietmar Maurer <dietmar@proxmox.com>
Cargo.toml
src/state/async_abort_guard.rs [new file with mode: 0644]
src/state/mod.rs

index 7950c06ffbb152a6f65a2dd40fd84bf192d4df6e..bdfe4f0bfa434a5d568f9744bd7b466b9a5bab25 100644 (file)
@@ -17,6 +17,7 @@ members = ["pwt-macros"]
 [dependencies]
 anyhow = "1.0"
 derivative = "2.2.0"
+futures = { version = "0.3", default-features = false, features = ["std"] }
 # If you need to use the development version of Yew
 # yew = { git = "https://github.com/yewstack/yew/", features = ["csr"] }
 # yew-router = { git = "https://github.com/yewstack/yew/" }
diff --git a/src/state/async_abort_guard.rs b/src/state/async_abort_guard.rs
new file mode 100644 (file)
index 0000000..7eff79c
--- /dev/null
@@ -0,0 +1,32 @@
+use futures::future::{abortable, AbortHandle, Future};
+
+/// Abort guard for async functions.
+pub struct AsyncAbortGuard {
+    abort_handle: AbortHandle,
+}
+
+impl AsyncAbortGuard {
+    /// Runs a Rust Future on the current thread.
+    ///
+    /// The future is aborted as soon as the returned guard gets dropped.
+    pub fn spawn<F>(future: F) -> Self
+    where
+        F: Future<Output = ()> + 'static,
+    {
+        let (future, abort_handle) = abortable(future);
+
+        wasm_bindgen_futures::spawn_local(async move {
+            match future.await {
+                Ok(()) => { /* do nothing */ }
+                Err(futures::future::Aborted) => { /* do nothing (maybe we want to log this?) */ }
+            }
+        });
+        AsyncAbortGuard { abort_handle }
+    }
+}
+
+impl Drop for AsyncAbortGuard {
+    fn drop(&mut self) {
+        self.abort_handle.abort();
+    }
+}
index 4c35398245ea4d5bfe447404508dcd15aa8abf8c..e5cfa9a1098ea343f541403c719adcc7d5a93c20 100644 (file)
@@ -4,6 +4,9 @@ use std::rc::Rc;
 
 use serde::{de::DeserializeOwned, Serialize};
 
+mod async_abort_guard;
+pub use async_abort_guard::AsyncAbortGuard;
+
 mod data_store;
 pub use data_store::{DataNode, DataNodeDerefGuard, DataStore};