What are the differences between GlobalScope, MainScope, and creating your own Scope in Kotlin Coroutines?
sobes.tech AI
Answer from AI
In Kotlin Coroutines, CoroutineScope defines the scope and lifecycle of coroutines.
-
GlobalScope — a global scope where coroutines live until the application terminates. Use it with caution, as coroutines are not automatically canceled and may lead to leaks.
-
MainScope — a scope intended for UI thread (e.g., in Android). It creates coroutines that run on the main thread and are usually canceled along with the component's lifecycle (e.g., Activity). Often used with calling
cancel()inonDestroy(). -
Creating your own Scope — allows controlling the lifecycle of coroutines by tying them to a specific object or component. For example, you can create a
CoroutineScopewith a specificJobandDispatcherto cancel all coroutines when the object is destroyed.
Example of creating your own Scope:
class MyViewModel : ViewModel() {
private val viewModelJob = Job()
private val scope = CoroutineScope(Dispatchers.Main + viewModelJob)
fun loadData() {
scope.launch {
// coroutine
}
}
override fun onCleared() {
super.onCleared()
viewModelJob.cancel() // cancel all coroutines
}
}
Thus, the choice of Scope depends on how you want to manage the lifetime of coroutines and their cancellation.