Function spawn_local

pub fn spawn_local<F>(future: F) -> JoinHandle<F::Output>
where
    F: Future + 'static,
    F::Output: 'static,

Spawns a !Send future on the current LocalSet or LocalRuntime.

This is possible when either using one of these types explicitly, or by opting to use the "local" runtime flavor in tokio::main:

#[tokio::main(flavor = "local")]

The spawned future will run on the same thread that called spawn_local.

The provided future will start running in the background immediately when spawn_local is called, even if you don't await the returned JoinHandle.

Panics

This function panics if called outside of a LocalSet or LocalRuntime.

Note that if tokio::spawn is used from within a LocalSet, the resulting new task will not be inside the LocalSet, so you must use spawn_local if you want to stay within the LocalSet.

Examples

With LocalSet:

use std::rc::Rc;
use tokio::task;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let nonsend_data = Rc::new("my nonsend data...");

let local = task::LocalSet::new();

// Run the local task set.
local.run_until(async move {
    let nonsend_data = nonsend_data.clone();
    task::spawn_local(async move {
        println!("{}", nonsend_data);
        // ...
    }).await.unwrap();
}).await;
# }

With local runtime flavor.

#[tokio::main(flavor = "local")]
async fn main() {
    let join = tokio::task::spawn_local(async {
        println!("my nonsend data...")
    });

   join.await.unwrap()
 }