GlobalScope
All coroutine work is managed by a CoroutineScope
. In the sample code, we are using GlobalScope
. As the name suggests, GlobalScope
is a global instance of a CoroutineScope
.
Primarily, a CoroutineScope
is responsible for canceling and cleaning up coroutines when the CoroutineScope
is no longer needed. `GlobalScopep will be set up to support the longest practical lifetime: the lifetime of the process that is running the Kotlin code.
However, while GlobalScope
is reasonable for samples like this one, more often you will want to use a scope that is a bit smaller in… well… scope. For example, if you are using coroutines in an Android app, and you are doing I/O to populate a UI, if the user navigates away from the activity or fragment, you may no longer need that coroutine to be doing its work. This is why Android, through the Jetpack, offers a range of CoroutineScope
implementations that will clean up coroutines when they are no longer useful.
Use of GlobalScope requires @DelicateCoroutinesApi
because GlobalScope
falls in the catetory have limited use-case and shall be used with care.
This is because kotlin coroutines follow a principle of structured concurrency which means that new coroutines can be only launched in a specific CoroutineScope which delimits the lifetime of the coroutine. for example if you start a coroutine with viewModelScope, then this coroutine will be cancelled as soon as ViewModel is destroyed.
but GlobalScope on the other hand creates global couroutines, their lifetime is the responsibility of programmer and if for some reason(network delay etc) these global coroutines can’t complete then they keep running and consuming system resources, this behaviour along with other issues, can cause memory leaks hence the DelicateCoroutinesApi.