https://kotlinlang.org logo
#coroutines
Title
# coroutines
z

zak.taccardi

12/27/2018, 7:20 PM
I want an
actor
that I can cancel and restart. Is that possible?
l

louiscad

12/27/2018, 7:22 PM
@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

zak.taccardi

12/27/2018, 7:24 PM
hmm that seems kind of messy
l

louiscad

12/27/2018, 7:24 PM
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

zak.taccardi

12/27/2018, 7:29 PM
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

Allan Wang

12/27/2018, 7:51 PM
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

zak.taccardi

12/27/2018, 7:55 PM
oh that’s obvious! just put a
launch
inside the
actor
and don’t block it
u

uli

12/27/2018, 7:55 PM
Use an actor to start/cancel coroutines for the long running job. Then it gets free immediately.
Ahh, you found out yourself 😁
l

louiscad

12/27/2018, 8:29 PM
@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

zak.taccardi

12/27/2018, 9:26 PM
my solution to this is here: https://kotlinlang.slack.com/archives/C1CFAFJSK/p1545945904107900 (though that lead me to my next problem). Thanks!
2 Views