Lilly
09/07/2021, 2:59 PMDispatchers.Default
. I'm asking because in my vms I have suspending fucntions as well as non-suspending functions (most of the time not expensive operations) and I'm wondering if there is a thumb of rule when to switch from main
to default
or should we always switch to default when we working outside the UI scope not matter how expensive the operation is?streetsofboston
09/07/2021, 3:02 PMTijl
09/07/2021, 4:02 PMsomeArray.filter { ... }
a “blocking” operation in your opinion?streetsofboston
09/07/2021, 4:12 PMTijl
09/07/2021, 4:14 PMsomeArray.filter
has input, output, and even if it does not wait for an external resource, it can still block your thread.streetsofboston
09/07/2021, 4:21 PMsomeArray
is huge or you have some code that is long running, then switching to the Dispatchers.Default may be warranted indeed.
But I've seen code that switches to Dispatchers.IO when it is just calling other suspending code (that does IO for example) and some simple transformations on the result. This not necessary.
I have not done any performance measures, but always switching to another dispatcher for even a 'little bit' of code may cost more than it saves.uli
09/07/2021, 4:24 PMwithContext
as small as possible. As @streetsofboston said, right around your blocking call. Or (@Tijl) of course around your computationally ‘expensive’ calls.
And remember, no rule without exceptions 🙂 While switching between Default and IO dispatcher is almost free, switching between IO/Default and Main comes at a cost. So some aggregation of blocking calls might sometimes be needed. But his is nothing for premature optimization.Tijl
09/07/2021, 5:35 PM