https://kotlinlang.org logo
#coroutines
Title
# coroutines
r

Riku

12/29/2019, 8:23 AM
I am honestly confused about what dispatchers to use server-side. Everything I have read so far has been focused on Android. Any recommendations for a general guide to when to use what dispatcher?
t

tseisel

12/29/2019, 11:12 AM
As a rule of thumb : •
Dispatchers.Main
may not exist on the server-side. •
Dispatchers.Default
should be used for computational tasks that requires CPU power such as reducing, transforming, etc. It has a pool of thread equal to the number of CPU cores to avoid overloading the CPU when scheduling too much work. •
<http://Dispatchers.IO|Dispatchers.IO>
, as its name suggests, should be used for blocking IO such as database access, file read/write and network communication. It has a larger pool of threads than
Default
because IO tasks don't need much CPU time, it just waits and blocks a thread.
r

Riku

12/29/2019, 12:30 PM
Thanks. what about long or continuously running coroutines, that stream values on a schedule?
For example, let’s say every 10 minutes my server will send a status update to the UI. I am guessing this should run on its own thread?
t

tseisel

12/29/2019, 3:03 PM
I think you can run that on
<http://Dispatchers.IO|Dispatchers.IO>
since it has the largest thread pool and your task requires some network connectivity. You could write it this way:
Copy code
launch(<http://Dispatchers.IO|Dispatchers.IO>) {
    while(true) {
        postStatusUpate(...)
        delay(10 * 60 * 1000) // 10 minutes in milliseconds
    }
}
Note that while the coroutine is suspended in
delay
it is not actively using a thread.
r

Riku

12/29/2019, 4:01 PM
👍
7 Views