I'm trying to figure out which Dispatcher to use in what case.
I read some documentation and came up with this:
Is this right?
What about Unconfined?
On Android, we typically use the Main dispatcher as the default one. If you use libraries that are suspending instead of blocking, and you don't do any complex calculations, in practice you can often use only Dispatchers. Main . If you do some CPU-intensive operations, you should run them on Dispatchers.
Kotlin coroutines use dispatchers to determine which threads are used for coroutine execution. To run code outside of the main thread, you can tell Kotlin coroutines to perform work on either the Default or IO dispatcher. In Kotlin, all coroutines must run in a dispatcher, even when they're running on the main thread.
Quoting definition of Global Scope from Kotlin's documentation– “Global scope is used to launch top-level coroutines which are operating on the whole application lifetime and are not cancelled prematurely.” GlobalScope creates global coroutines and these coroutines are not children of some specific scope.
You're right in your assumptions about the dispatcher types. Unconfined dispatcher –
A coroutine dispatcher that is not confined to any specific thread
Unconfined dispatcher is appropriate when coroutine does not consume CPU time nor updates any shared data (like UI) that is confined to a specific thread.
You can read more about it here and here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With