Function slint::spawn_local

source ·
pub fn spawn_local<F>(
    fut: F
) -> Result<JoinHandle<<F as Future>::Output>, EventLoopError>
where F: Future + 'static,
Expand description

Spawns a Future to execute in the Slint event loop.

This function is intended to be invoked only from the main Slint thread that runs the event loop. The event loop must be initialized prior to calling this function.

For spawning a Send future from a different thread, this function should be called from a closure passed to invoke_from_event_loop().

This function is typically called from a UI callback.

§Example

slint::spawn_local(async move {
    // your async code goes here
}).unwrap();

§Compatibility with Tokio and other runtimes

The runtime used to execute the future on the main thread is platform-dependent, for instance, it could be the winit event loop. Therefore, futures that assume a specific runtime may not work. To overcome this, these futures should be executed in a thread where the specific runtime is running.

For Tokio, this can be achieved by awaiting tokio::spawn in the future passed to slint::spawn_local.

// In your main function, create a runtime that runs on the other threads
let tokio_runtime = tokio::runtime::Runtime::new().unwrap();

// ...
// Within the UI thread (for example in a callback handler)
slint::spawn_local(async move {
    let result = tokio_runtime.spawn(async move {
        // This code is running on the Tokio runtime's thread, you can await futures that depends on Tokio here.
        42
    }).await.unwrap();
    // now we are back on the UI thread so we can do something with the result on the UI thread
    assert_eq!(result, 42);
}).unwrap();