Pacane
03/26/2020, 2:19 PMsuspend
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?araqnid
03/26/2020, 2:21 PMval coroutineScope = CoroutineScope(EmptyCoroutineContext)
in some owning objectcancel
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 scopePacane
03/26/2020, 2:22 PMaraqnid
03/26/2020, 2:23 PMPacane
03/26/2020, 2:24 PMcancel
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?
araqnid
03/26/2020, 2:29 PMlaunch
job will be a child of the scope Joblaunch
, that will propagate up and then across to its siblings as wellSupervisorJob()
to the context passed to CoroutineScope
and then the cancelled child jobs won’t cause armageddonGlobalScope
(which doesn’t have a Job at all, so all the child launch
jobs wouldn’t have anywhere to propagate their failure/cancellation to)Pacane
03/26/2020, 2:35 PM