Reputation: 15309
I'm trying to run a task in the background on Android, and I was wondering whether I need to specify GlobalScope.launch(Dispatchers.IO) { ... }
or if a simple GlobalScope.launch { ... }
is enough. My worry is whether the second form launches the coroutine in the main or a background/IO thread?
According to Android documentation,
launch
doesn't take aDispatchers.IO
parameter. When you don't pass aDispatcher
to launch, any coroutines launched fromviewModelScope
run in the main thread.
According to Kotlin documentation,
The default dispatcher that is used when coroutines are launched in GlobalScope is represented by Dispatchers.Default and uses a shared background pool of threads, so
launch(Dispatchers.Default) { ... }
uses the same dispatcher asGlobalScope.launch { ... }
.
I know coroutines were experimental until recently, and Android-Kotlin vs pure-Kotlin development are different, but these statements seem contradictory to me.
Upvotes: 5
Views: 2747
Reputation: 8096
GlobalScope has EmptyCoroutineContext which implies Dispatchers.Default will be used when directly launching within it.
Example demonstrating the behavior: https://pl.kotl.in/cLy3UfuZO
My worry is whether the second form launches the coroutine in the main or a background/IO thread?
It'll launch it into CommonPool under Dispatchers.Default which shares max thread same as number of cores in your CPU, for instance if your CPU has 6 cores then there will be a max limit of 6 threads. Dispatchers.IO however allows upto borrowing 64 threads from the CommonPool. Dispatchers.Main is single threaded.
Story of viewModelScope
is different, that scope contains Dispatchers.Main
as its default dispatcher to launch in. You can create a scope like this CoroutineScope(Dispatchers.Main)
so that every launch without specifying dispatcher will launch in the Main similar to the viewModelScope
.
Upvotes: 6