Thomas
08/19/2024, 3:49 AMwithContext(currentCoroutineContext()) { /*...*/ }
(alternatively coroutineScope { /*...*/ }
, which should be the same in behaviour)
2. with(CoroutineScope(currentCoroutineContext())) { /*...*/ }
The difference in behaviour is that, in (1) withContext
does not return until all child coroutines started under its block have completed;
whereas (2) does not wait for its child coroutines to complete. For example:
runBlocking{
//(1)
withContext(currentCoroutineContext()) {
launch{
delay(100)
print("1")
}
}
print("2")
}
//prints "12"
and
runBlocking{
//(2)
with(CoroutineScope(currentCoroutineContext())) {
launch{
delay(100)
print("2")
}
}
print("1")
}
//prints "12"
*
My question is, nobody ever does (2), the "non child coroutine waiting" variant, but why?
Could we say that nobody does (2) because it violates the coroutine library's design philosophy where concurrency must be explicit?Thomas
08/19/2024, 6:23 AMrunBlocking{
launch{
delay(100)
print("2")
}
print("1")
}
Thomas
08/19/2024, 6:25 AMfun CoroutineScope.f1(){
launch{
delay(100)
print("2")
}
print("1")
}
for immediate return, or:
suspend fun f2() = coroutineScope{
launch{
delay(100)
print("1")
}
print("2")
}
for coroutine execution suspensionuli
08/19/2024, 6:34 AMCoroutineScope(currentCoroutineContext())
could be garbage collected before the jobs are complete. Whenever you create a new CoroutineScope, you should also hold a strong reference to it.Thomas
08/19/2024, 6:46 AMSam
08/19/2024, 6:55 AMCould we say that nobody does (2) because it violates the coroutine library's design philosophy where concurrency must be explicit?Yes, exactly. By convention, a suspending function always waits for all its work to finish before returning. Your summary of the original problem, and the two correct patterns in your later message, look spot on to me.
Thomas
08/19/2024, 6:57 AMSam
08/19/2024, 6:58 AMCoroutineScope
instance itself might become unreachable, but it's only a wrapper for the coroutineContext
inside.uli
08/19/2024, 7:24 AMlouiscad
08/19/2024, 7:26 AMSam
08/19/2024, 7:27 AMlouiscad
08/19/2024, 7:27 AMThomas
08/19/2024, 7:27 AMThomas
08/19/2024, 7:45 AMSam
08/19/2024, 7:46 AMJob
hierarchy. Since the parent job keeps a reference to the child, I don't think the linked issue would affect your code.louiscad
08/19/2024, 7:48 AMThomas
08/19/2024, 7:58 AM