Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin Coroutines choosing Dispatcher

I'm trying to figure out which Dispatcher to use in what case.

I read some documentation and came up with this:

  • Default → CPU work
  • Main → main (update UI)
  • Unconfined
  • IO → writing file / network tasks

Is this right?

What about Unconfined?

like image 404
solaza Avatar asked Jul 19 '19 09:07

solaza


People also ask

What is the default dispatcher in coroutines?

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.

What is dispatcher in Kotlin coroutines Android?

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.

When should I use GlobalScope coroutines?

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.


1 Answers

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

like image 58
Andrei Tanana Avatar answered Oct 11 '22 13:10

Andrei Tanana