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
Yes, in priciple you are right, here more details.
Scope
Context
The context determines on which thread the coroutines will run. There are four options:
Dispatchers.Default - for CPU intense work (e.g. sorting a big list)Dispatchers.Main - what this will be depends on what you've added to your programs runtime dependencies (e.g. kotlinx-coroutines-android, for the UI thread in Android)Dispatchers.Unconfined - runs coroutines unconfined on no specific thread Dispatchers.IO - for heavy IO work (e.g. long-running database queries) The following example brings both scope and context together. It creates a new scope in which the coroutines will run (if not changed) on a thread designated for IO work and cancels them via their scope.
val scope = CoroutineScope(context = Dispatchers.IO)
val job = scope.launch {
val result = suspendFunc1()
suspendFunc2(result)
}
// ...
scope.cancel() // suspendFunc1() and suspendFunc2() will be cancelled