Function spawn

Source
pub fn spawn(future: impl Future<Output = ()> + 'static) -> TaskHandle
Available on since_api="4.2" only.
Expand description

Create a new async background task.

This function allows creating a new async task in which Godot signals can be awaited, like it is possible in GDScript. The TaskHandle that is returned provides synchronous introspection into the current state of the task.

Signals can be converted to futures in the following ways:

Signal typeSimple futureFallible future (handles freed object)
UntypedSignal::to_future()Signal::to_fallible_future()
TypedTypedSignal::to_future()TypedSignal::to_fallible_future()

§Panics

If called from any other thread than the main thread.

§Examples

With typed signals:

#[derive(GodotClass)]
#[class(init)]
struct Building {
   base: Base<RefCounted>,
}

#[godot_api]
impl Building {
   #[signal]
   fn constructed(seconds: u32);
}

let house = Building::new_gd();
godot::task::spawn(async move {
    println!("Wait for construction...");

    // Emitted arguments can be fetched in tuple form.
    // If the signal has no parameters, you can skip `let` and just await the future.
    let (seconds,) = house.signals().constructed().to_future().await;

    println!("Construction complete after {seconds}s.");
});

With untyped signals:

let node = Node::new_alloc();
let signal = Signal::from_object_signal(&node, "signal");

godot::task::spawn(async move {
    println!("Starting task...");

    // Explicit generic arguments needed, here `()`:
    signal.to_future::<()>().await;

    println!("Node has changed: {}", node.get_name());
});