Skip to content

Commit

Permalink
feat: Add JoinHandle::abort() (#2877)
Browse files Browse the repository at this point in the history
Co-authored-by: Lucas Nogueira <lucas@tauri.studio>
  • Loading branch information
xuchaoqian and lucasfernog authored Nov 13, 2021
1 parent 3de67cb commit ad16975
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changes/join-handle-abort.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"tauri": patch
---

Added `abort` method to `tauri::async_runtime::JoinHandle`.
24 changes: 24 additions & 0 deletions core/tauri/src/async_runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,17 @@ static RUNTIME: OnceCell<Runtime> = OnceCell::new();
#[derive(Debug)]
pub struct JoinHandle<T>(TokioJoinHandle<T>);

impl<T> JoinHandle<T> {
/// Abort the task associated with the handle.
///
/// Awaiting a cancelled task might complete as usual if the task was
/// already completed at the time it was cancelled, but most likely it
/// will fail with a cancelled `JoinError`.
pub fn abort(&self) {
self.0.abort();
}
}

impl<T> Future for JoinHandle<T> {
type Output = crate::Result<T>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
Expand Down Expand Up @@ -108,4 +119,17 @@ mod tests {
let handle = handle();
assert_eq!(handle.block_on(async { 0 }), 0);
}

#[tokio::test]
async fn handle_abort() {
let handle = handle();
let join = handle.spawn(async { 5 });
join.abort();
if let crate::Error::JoinError(raw_box) = join.await.unwrap_err() {
let raw_error = raw_box.downcast::<tokio::task::JoinError>().unwrap();
assert!(raw_error.is_cancelled());
} else {
panic!("Abort did not result in the expected `JoinError`");
}
}
}

0 comments on commit ad16975

Please sign in to comment.