I want an `actor` that I can cancel and restart. I...
# coroutines
z
I want an
actor
that I can cancel and restart. Is that possible?
l
@zak.taccardi Only if you swap the actor and point to the new reference, or if you implement a
SendChannel
that delegates to an
actor
you can swap from under.
z
hmm that seems kind of messy
l
Or you can make your actor accept a cancel but not too hard signal, then make it accept a restart now signal. You could launch coroutines inside of it and cancel this previously running coroutine when such a signal arrives
z
I’ll explain my use case. - I want to kick off some long running work on demand. - If a request comes in to kick off this long running work while it’s already running, I want to cancel the existing coroutine that is doing the long running work, and restart it. - I never want two instances of the long running work to be done in parallel
normally I would use an actor, but that would queue up the long running work one after the either
the long running work could just be a network call in that case
a
As a note from other talks, don't you want to avoid using
suspend
and extend
CoroutineScope
at the same time? The action looks like it should be just
suspend
since it's long running
z
oh that’s obvious! just put a
launch
inside the
actor
and don’t block it
u
Use an actor to start/cancel coroutines for the long running job. Then it gets free immediately.
Ahh, you found out yourself 😁
l
@Allan Wang The linked function (named
consumeEachAndCancelPrevious
) is just a suspend function and creates its own local scope. The other one above it is a solution to this issue: https://github.com/Kotlin/kotlinx.coroutines/issues/328
z
my solution to this is here: https://kotlinlang.slack.com/archives/C1CFAFJSK/p1545945904107900 (though that lead me to my next problem). Thanks!