If some code does (de)serialization or other poten...
# coroutines
m
If some code does (de)serialization or other potentially CPU-intensive work like using a template system to build HTML (all in-memory), do you do delegate the execution to the
Default
dispatcher? Or do you you accept that the current dispatcher (whatever it is) is potentially blocked for a few milliseconds? I have the habit of wrapping such code in
withContext(Dispatchers.Default) { … }
, but I’m not actually sure if that’s necessary. Or maybe it’s even a bad idea.
k
Why would you think it’s a bad idea? I say that’s a good habit to have, since you don’t want to block whatever thread you’re on. What if your suspend function is redirected to
main
dispatcher? It’d mean you’ll block UI, if you don’t change the thread
☝️ 2
m
Switching dispatchers also doesn’t come free. But I guess it’s negligible compared to serialization/templating work. But yeah, makes sense for
Main
dispatchers. I mostly have such cases in back-end where I don’t use
Main
.
c
i think its also important in the backend, and can severly affect concurrency if you block your non blocking io thread too long
l
Switching between IO and Default is almost free, you just pay the lambda, but the threads don't switch, the same thread switches dispatcher seamlessly.
u
Do add to @louiscad if you are only using the 3 pre-existing dispatcher (Default,Main,IO), thread switching is only involved if you were initially on the main dispatcher. And that’s when you need it. If you are currently dispatched on IO or Default dispatcher withContext(Dispatcher.Default) should keep execution on the same thread and therefor be almost free.
k
Interesting - is this behavior documented somewhere?