What is Coroutine scope ?
- Coroutine scope is a constraint in which coroutines are executed
- In Android , these scopes also define the lifespan of the coroutines they embrace.
There are 3 types of Coroutine scopes
- GlobalScope
- LifeCycleScope
- ViewModelScope
GlobalScope
- The coroutines launched in this scope live long as the application does
- If the coroutines finishes the job , then it is destroyed and will not kept alive as long as application does
Code
/**
* globalscope
*/
// print Main thread name
Log.d("Coroutines", "Main ${Thread.currentThread().name.toString()}")
GlobalScope.launch {
// run this coroutine till application is killed .
while (true){
// delay for 2 seonds
delay(2000)
// print thread name
Log.d("Coroutines", "GlobalScope ${Thread.currentThread().name.toString()}")
}
}
Log.d("Coroutines", "End of GlobalScope ")
Output
17:03:32.552 D/Coroutines: Main main
17:03:32.596 D/Coroutines: End of GlobalScope
17:03:34.607 D/Coroutines: GlobalScope DefaultDispatcher-worker-1
17:03:36.609 D/Coroutines: GlobalScope DefaultDispatcher-worker-1
17:03:38.610 D/Coroutines: GlobalScope DefaultDispatcher-worker-1
17:03:39.716 D/Coroutines: onStop
17:03:39.720 D/Coroutines: onDestroy
17:03:40.615 D/Coroutines: GlobalScope DefaultDispatcher-worker-1
LifecycleScope
- The coroutines launched in this scope live long as the activity or fragment in which the lifeCycleScope is launched
Code
/**
* lifecyclescope
*/
// print Main thread name
Log.d("Coroutines", "Main ${Thread.currentThread().name.toString()}")
lifecycleScope.launch(Dispatchers.IO){
// run this coroutine till activity is killed .
while (true){
// delay for 2 seconds
delay(2000)
// print thread name
Log.d("Coroutines", "lifecycleScope ${Thread.currentThread().name.toString()}")
}
}
Log.d("Coroutines", "End of lifecycleScope )
Output
17:10:24.446 D/Coroutines: Main main
17:10:24.499 D/Coroutines: End of lifecycleScope
17:10:26.517 D/Coroutines: lifecycleScope DefaultDispatcher-worker-1
17:10:28.519 D/Coroutines: lifecycleScope DefaultDispatcher-worker-1
17:10:30.488 D/Coroutines: onStop
17:10:30.504 D/Coroutines: onDestroy
ViewModelScope
- The coroutine launched in this cope live long as the viewmodel is alive
Please leave your comments to improve.
Happy Coding