improve spawn docs

This commit is contained in:
Rob Ede 2021-09-01 20:51:39 +01:00
parent 9df1b45fd1
commit 82217b4984
No known key found for this signature in database
GPG Key ID: 97C636207D3EF933
2 changed files with 28 additions and 2 deletions

View File

@ -155,10 +155,36 @@ pub mod task {
pub use tokio::task::{spawn_blocking, yield_now, JoinError, JoinHandle}; pub use tokio::task::{spawn_blocking, yield_now, JoinError, JoinHandle};
} }
/// Spawns a future on the current thread. /// Spawns a future on the current thread as a new task.
///
/// If not immediately awaited, the task can be cancelled using [`JoinHandle::abort`].
///
/// The provided future is spawned as a new task; therefore, panics are caught.
/// ///
/// # Panics /// # Panics
/// Panics if Actix system is not running. /// Panics if Actix system is not running.
///
/// # Examples
/// ```
/// # use std::time::Duration;
/// # actix_rt::Runtime::new().unwrap().block_on(async {
/// // task resolves successfully
/// assert_eq!(actix_rt::spawn(async { 1 }).await.unwrap(), 1);
///
/// // task panics
/// assert!(actix_rt::spawn(async {
/// panic!("panic is caught at task boundary");
/// })
/// .await
/// .unwrap_err()
/// .is_panic());
///
/// // task is cancelled before completion
/// let handle = actix_rt::spawn(actix_rt::time::sleep(Duration::from_secs(100)));
/// handle.abort();
/// assert!(handle.await.unwrap_err().is_cancelled());
/// # });
/// ```
#[inline] #[inline]
pub fn spawn<Fut>(f: Fut) -> JoinHandle<Fut::Output> pub fn spawn<Fut>(f: Fut) -> JoinHandle<Fut::Output>
where where

View File

@ -1,4 +1,5 @@
use std::{ use std::{
future::Future,
sync::{ sync::{
atomic::{AtomicBool, Ordering}, atomic::{AtomicBool, Ordering},
mpsc::channel, mpsc::channel,
@ -9,7 +10,6 @@ use std::{
}; };
use actix_rt::{Arbiter, System}; use actix_rt::{Arbiter, System};
use futures_core::Future;
use tokio::sync::oneshot; use tokio::sync::oneshot;
#[test] #[test]