https://kotlinlang.org logo
Title
p

Pacane

03/26/2020, 2:19 PM
Hi, I'm trying to understand how to use coroutines in my use case... I am using the JVM (and not android). My code doesn't current use coroutines, I'm using Java CompleteableFuture to do async work. The type of work I'm doing is Fire and Forget type of stuff (I have an infinite while loop doing video/image processing. I currently have no
suspend
functions, but I could get my code to work with the
GlobalScope.launch
function. Now I've read in several places that I should avoid using the GlobalScope. So my question is, how can I create a coroutine scope for a given method (not the main) and still use coroutines for a fire and forget type of work. I've tried doing something like
fun myMethod() = runBlocking { .... }
and then inside use
CoroutineScope.launch
but the code after the
launch
block is still blocked by the
launch
block. What could I do to make this work?
a

araqnid

03/26/2020, 2:21 PM
An outer scope can be created at any time, just seeded with a coroutine context: just stick a
val coroutineScope = CoroutineScope(EmptyCoroutineContext)
in some owning object
the only other thin you should do is
cancel
the scope at some appropriate time — so if you already have a
close()
or
stop()
method, that’s the time: the object owning the scope is going away, so cancel the scope
p

Pacane

03/26/2020, 2:22 PM
Yes, I do have that, thank you
a

araqnid

03/26/2020, 2:23 PM
alternatively, it sounds like you could just stick this above your while loop and cancel it in a finally block in case of errors breaking the loop?
p

Pacane

03/26/2020, 2:24 PM
and also, what's the difference between the
cancel
on the Job returned by
launch
and the coroutine scope's
cancel
?
alternatively, it sounds like you could just stick this above your while loop and cancel it in a finally block in case of errors breaking the loop?
yes that sounds about right
a

araqnid

03/26/2020, 2:29 PM
well, they are different nodes in the Job hierarchy - the
launch
job will be a child of the scope Job
CoroutineScope() will add a fresh Job to the EmptyCoroutineContext, given the invocation above
this does mean that all your jobs are now linked together- if you cancel one of the jobs returned from
launch
, that will propagate up and then across to its siblings as well
if that’s not what you want, you should add
SupervisorJob()
to the context passed to
CoroutineScope
and then the cancelled child jobs won’t cause armageddon
that would more closely resemble using
GlobalScope
(which doesn’t have a Job at all, so all the child
launch
jobs wouldn’t have anywhere to propagate their failure/cancellation to)
p

Pacane

03/26/2020, 2:35 PM
Awesome, thanks for the explanation 🙂