简体   繁体   中英

Does Kotlin's launch start a coroutine in the main or a background thread?

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 a Dispatchers.IO parameter. When you don't pass a Dispatcher to launch, any coroutines launched from viewModelScope 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 as GlobalScope.launch {... } .

I know coroutines were experimental until recently, and Android-Kotlin vs pure-Kotlin development are different, but these statements seem contradictory to me.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM