In my Android application, I have a usecase in which I need to run a bit of code inside a loop for as long as the app is running.
Example code:
fun exampleRunCodeInLoop() {
viewModelScope.launch(Dispatchers.Default) {
while (true) {
delay(5000) // Wait for 5 seconds
// @param someCondition is just an example for the if statement
if (someCondition == true) {
withContext(Dispatchers.Main) {
// Do something on Main thread
}
}
}
}
}
I am confused regarding which Dispatcher
to use for the launch
block to get the best performance. Should I use Default
, IO
or just run everything on Main
?
CodePudding user response:
Dispatchers.Default
as it is designed to be optimal for computations, by using a shared pool of threads that contains a maximum number of threads that is equal to the number of CPU cores
Dispatchers.IO
in case your blocking the thread, waiting for a response without doing heavy computational logic
CodePudding user response:
At least here's the usage I did with coroutine dispatcher.
Dispatchers.Default
- I usually use this when only doing CPU-intensive tasks to parallel with the current task on the main thread, it has a fixed size hardcoded to the number of available processors, because that's what makes sense for CPU-intensive tasks. Use with operation like loops, math operations, data/image manipulations.
Dispatchers.IO
- is designed for offloading blocking IO tasks to a shared pool of threads. Use if you still need more threads than cores if you're doing blocking IO, e.g., Database query is an IO operation or network calls
Dispatchers.Main
- A coroutine dispatcher that is confined to the Main thread operating with UI objects. This dispatcher can be used either directly or via MainScope factory. Usually such dispatcher is single-threaded. Usually used when you are done or finished with the background task from IO or Default to forecast whatever results from operations you've done to the UI or Main Thread.