Can anyone explain the difference between them? I think scope provides a reference(e.g. Job) to cancel them and context provides a reference to underlying thread. Is that so
CoroutineScope
has-a CoroutineContext
.
For example if you have:
runBlocking { // defines coroutineScope
launch(Dispatchers.Default) { //inherits coroutineScope but changes context
}
}
runBlocking
defines a CoroutineScope
(learn about it here) which launch
inherits. The context is being overridden by explicitly specifying a dispatcher here. If you look at the definition of launch
, you can see that it takes an optional CoroutineContext
:
public fun CoroutineScope.launch(
context: CoroutineContext = EmptyCoroutineContext,
...
)
Another part of the context would be the coroutine's name:
launch(CoroutineName("launchMe") + Dispatchers.Default) {
println("")
}