Search code examples
rustrust-tokiotauriprotocol-handler

What is the recommended technique for calling an async function within a tauri protocol handler?


In order to call an async function within a Tauri protocol handler I'm successfully using futures::executor::block_on as described in the following SO answer. Link: https://stackoverflow.com/a/66280983/4802953

But the answer discourages using this technique so I am not sure if this is the recommended way to call an async function from within a Tauri protocol handler.

A simplified version of my code is as follows:

#[tokio::main]
async fn main() {
    tauri::Builder::default()
        .register_uri_scheme_protocol("myprot", move |_app, req| {
            let handle = tokio::runtime::Handle::current();
            let _guard = handle.enter();

            futures::executor::block_on(async move { handle_protocol_myprot(&req).await })
        })
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

If you can use Tauri 2.0 (currently beta), there's a new method register_asynchronous_uri_scheme_protocol that would let you have async call inside.


Solution

  • I got the following response from FabianLars on the Tauri discord:

    Tauri has an easier to use block_on function: https://docs.rs/tauri/latest/tauri/async_runtime/fn.block_on.html (you can import it and directly call it without the need for a handle first). block_on is generally good enough if the task is not taking too much time.

    Speaking of handles, you have to give tauri one to your main tokio runtime: https://docs.rs/tauri/latest/tauri/async_runtime/fn.set.html.

    If you do not need to wait for the result to return from the protocol handler you can of course use spawn instead.

    If both of that doesn't work for you, v2 will have an async protocol where you return the protocol from inside the spawned task: https://docs.rs/tauri/2.0.0-beta/tauri/struct.Builder.html#method.register_asynchronous_uri_scheme_protocol Ref: https://discord.com/channels/616186924390023171/1224053280565497896