CLOVIS
03/18/2025, 5:30 PMcoroutineScope {} have a CoroutineContext parameter?
This seems legitimate to me:
coroutineScope(<http://Dispatchers.IO|Dispatchers.IO>) {
// …
}
AFAIK, the current way to do this is to surround everything with a withContext callkevin.cianfarini
03/18/2025, 5:37 PMcoroutineScope isn't created with the intent to switch contexts but to create many children of the current context.
If it had a context parameter there would be no functional difference between this an withContextephemient
03/18/2025, 5:45 PMcoroutineScope {} = withContext(EmptyCoroutineContext) {}kevin.cianfarini
03/18/2025, 5:47 PMwithContext is a less efficient function than coroutineScope simply because it's expected to do more things.ephemient
03/18/2025, 5:51 PMkevin.cianfarini
03/18/2025, 5:53 PMcoroutineScope function is essentially copy-pasted into one of the fast paths of withContext.kevin.cianfarini
03/18/2025, 5:53 PMcoroutineScope is for the concurrent decomposition of work whereas withContext has a much broader remit. For example, it's not immediately obvious to people what withContext(EmptyCoroutineContext) would even be doing.Oleg
03/18/2025, 8:28 PMwithContext does some extra synchronization, doesn't it? https://www.baeldung.com/kotlin/withcontext-vs-async-awaitephemient
03/18/2025, 8:30 PMcoroutineScopeOleg
03/18/2025, 8:41 PMkevin.cianfarini
03/18/2025, 11:12 PMsuspend fun foo() {
withContext(Dispatchers.Default) {
println("first")
}
withContext(Dispatchers.Default) {
println("second")
}
}kevin.cianfarini
03/18/2025, 11:12 PMkevin.cianfarini
03/18/2025, 11:12 PMcoroutineScopeOleg
03/19/2025, 7:27 AMJP Sugarbroad
03/19/2025, 8:27 PMcoroutineScope is to give you access to the methods on CoroutineScope, like launch. If you just want to switch contexts, use withContext.