Why would I not always use Dispatchers.Main.immedi...
# coroutines
u
Why would I not always use Dispatchers.Main.immediate (over the nonimmediate)?
👀 1
b
In case the code you want run can be queued for later instead. Typically, you don't want to hold the main thread in a single function for too long, especially if that thread is being used to update UI. I typically use
immediate
if it's possible the thread backing the coroutine is already in main, and should be run at that point in time. Else, I let whatever is handling the main thread to schedule as necessary.
🙏 1
u
not sure what you mean "dont want to hold the main thread in a single function for too long" .. if the function is blocking main thread, then what does the dispatcher matter
b
In most cases, it probably won't matter what you use. But if you are developing something like a game, it might make sense to allow the thread to perform any pending updates first before updating hundreds of other objects. By using
immediate
, you take finer control over what runs first.
f
Because you might block the main thread for too much if you're not switching context to do long running task and your UI will wait to be updated a.k.a the birth of performance degradation (frame drops)
2
m
I am thinking how to compare it to something I know, and what comes to my mind for Android is Handler with main looper.
Copy code
// Get a handler that can be used to post to the main thread
Handler mainHandler = new Handler(context.getMainLooper());

Runnable myRunnable = new Runnable() {
    @Override 
    public void run() {....} // This is your code
};
<http://mainHandler.post|mainHandler.post>(myRunnable);
This was used to call main thread from other thread. I would compare it with
Dispatchers.Main
since you don't need to execute immediately. Would you agree?