How to make an abortable async background task with actix?

I'm trying to figure out how to set up an abort handle for a task started with actix::spawn.

This earlier thread seems to be what I want to do, however, it's using async_std instead of actix and attempting to pass the output of Abortable::new to actix::spawn gives a type mismatch:

type mismatch resolving `<Abortable<impl futures::Future> as futures::Future>::Output == ()`
expected unit type `()`
        found enum `std::result::Result<(), Aborted>`

Is there any way to do this?

You shouldn't need to use Abortable - the JoinHandle returned by spawn has an abort method.

If you did want to use Abortable however you can do async { let _ = abortable.await; } to convert a future that resolves to a Result into a future that resolves to a ().

2 Likes

For more details, see this SO answer. As written in the answer, the way you spawn an abortable task with tokio::spawn is the following:

let (task, handle) = abortable(start());
tokio::spawn(task);

To do the same with actix_rt::spawn, you can do it like this:

let (task, handle) = abortable(start());
actix_rt::spawn(async move { drop(task.await); });

Of course, as @Kestrer says, you don't need to do this as aborting is built in to the JoinHandle already.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.