I am honestly confused about what dispatchers to u...
# coroutines
r
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
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
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
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
👍