natario1
03/23/2021, 10:16 AMcoroutineScope { }
vs. just executing them in the outer scope? Assuming the outer context has a regular Job
.Big Chungus
03/23/2021, 10:20 AMnatario1
03/23/2021, 10:25 AMsuspendFun0()
suspendFun1()
withContext(otherContext) {
suspendFun2()
}
vs.
coroutineScope {
suspendFun0()
suspendFun1()
withContext(otherContext) {
suspendFun2()
}
}
In both cases I reach the end of the code when all ops have finished. Or get an exception if they fail.
And since we have a regular Job
in both cases, failure of any child will cancel everything else (just maybe in a different order), in both cases.coroutineScope { }
is just to ensure that current job is a Job()
(not supervised) so if you already know that, coroutineScope {} is useless. I can't tell whether this is the case from documentation thoughBig Chungus
03/23/2021, 10:35 AMfun CoroutineScope.test1() {
suspendFun1() //suspends
launch { ... } //does not suspend
suspendFun2() //executes basically immediately after suspendFun1() and suspends again
// returns after suspendFun2() resumes, does not wait for launched job
}
suspend fun test2() {
coroutineScope {
suspendFun1() //suspends
launch { ... } //does not suspend
suspendFun2() //executes basically immediately after suspendFun1() and suspends again
} // suspends until all things inside resume, including launched job
// returns after coroutineScope() resumes
}
Alex Vasilkov
03/23/2021, 10:35 AMcoroutineScope
is used when you need access to a scope to launch other jobs, if you just need to launch a few suspending functions then you don’t need it indeed.Albert Chang
03/23/2021, 10:36 AMcoroutineScope
.Big Chungus
03/23/2021, 10:37 AMsuspend fun printAllValues(list:List<Any>) {
val workerCount = 5
val chunks = list.chunk(list.size / 5)
coroutineScope {
repeat(workerCount) { i ->
launch { // Prints each chunk in parallel
chunks[i].forEach(::println)
}
}
}
// will return once ALL chunks are printed
}
natario1
03/23/2021, 10:53 AMlaunch
, it shows an async
but it then uses async.await()
so basically makes it look like a regular scope.Erik
03/23/2021, 10:59 AMnatario1
03/23/2021, 11:03 AMJob
🙂 but thanks for helping