Search code examples
rustasync-awaitrust-tokio

Passing callback into tokio task


I have a function that takes a callback as a parameter:

fn my_function (on_complete: Box<dyn FnOnce(bool)) {
    // Do some work
    on_complete(false);
}

The work I do before calling is pretty heavy though, so I'm trying to spawn it off into a task:

fn my_function (on_complete: Box<dyn FnOnce(bool)) {
    tokio::spawn(async move{
        // Do some work
        on_complete(false);
    });
}

This is giving me all sorts of ownership issues, namely that my Box can't be safely shared across threads. I've tried a number of things to get around this, including obvious ones like borrowing and more traditional threading solutions like passing it as an Arc>, but can't seem to get anywhere.

Any suggestions on how to do this correctly?


Solution

  • You need to mark your boxed callback as thread-safe with Send:

    fn my_function (on_complete: Box<dyn FnOnce(bool) + Send>) {
    //                                               ^^^^^^^
        tokio::spawn(async move{
            // Do some work
            on_complete(false);
        });
    }