thiagoretondar
07/18/2019, 12:35 PMJobs
stored in a List<Job>
are completed?streetsofboston
07/18/2019, 12:45 PMstreetsofboston
07/18/2019, 12:47 PMcoroutineScope{ ...}
(notice the lowercase 'c'). The call to coroutineScope suspends and only resumes after all it's child Coroutines (Jobs) have completed.thiagoretondar
07/18/2019, 1:01 PMcoroutineScope
because I need the method who invoked those jobs
returns asap.
My method is like this:
fun process(): UUID {
// get a list of things to do
val listOfThings = listOf<Any>()
val jobs = listOfThings.map { thing ->
GlobalScope.launch {
doProcess(thing) // suspended function
}
}
// when all jobs are completed, do other thing
return UUID.randomUUID()
}
I want return UUID.randomUUID()
asap but before it, I want to “schedule” a method to be called after all jobs are completedstreetsofboston
07/18/2019, 1:21 PMCoroutineScope.launch
call, which will return immediately.kevinherron
07/18/2019, 1:33 PMrunBlocking { jobs.forEach { it.join() } }
thiagoretondar
07/18/2019, 2:19 PMrunBlocking
won’t work for me. I will do it with CoroutineScope.launch
. Thanks!Alexjok
07/18/2019, 2:20 PMfun process(): UUID = runBlocking {
// get a list of things to do
val listOfThings = listOf<Any>()
val jobs = listOfThings
.map { thing -> launch { doProcess(thing) } }
.joinAll()
// when all jobs are completed, do other thing
return@runBlocking UUID.randomUUID()
}
Alexjok
07/18/2019, 2:20 PMstreetsofboston
07/18/2019, 2:24 PMGlobalScope
, though. I’m not aware about your exact use-case, but it is advised to avoid it 🙂thiagoretondar
07/18/2019, 2:25 PMAlexjok
07/18/2019, 2:25 PMAlexjok
07/18/2019, 2:26 PMstreetsofboston
07/18/2019, 2:31 PMprocess
and extension function on a CoroutineScope: fun CoroutineScope.process()
.
This allows structured concurrency, especially cancelling the entire ‘process()’ request when the calling/interested party is no longer interested and canceling the entire thing (through calling the CoroutineScope.cancel()
)
If the process
method is part of a class with its own lifecycle and needs to run as long as instances of that class are active, create a CoroutineScope
for that and use that one for use in the process()
function.