A little follow up question. If some API exposes a...
# coroutines
d
A little follow up question. If some API exposes a suspend function, but the implementation detail is that this function will do a lot of IO-bound work, is it OK to wrap its entire body in
withContext
?
Copy code
suspend fun callMe() {
  withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
    doAllWorkHere()
  }
}
If
withContext
is not used then I risk that the caller will use a context which is bad for this particular workload. Or is there some other well established pattern or design consideration for such cases?
j
Suspend functions should not block threads by convention, so it's actually good practice that the
suspend
function internally uses the appropriate IO context in that case. For reference: https://elizarov.medium.com/blocking-threads-suspending-coroutines-d33e11bf4761
👀 1
âž• 1
e
the only note I would add to that is: it may be useful to have some mechanism to inject a different dispatcher for tests
j
Yep, you could add a custom
coroutineContext
as argument, which defaults to
<http://Dispatchers.IO|Dispatchers.IO>
.
d
Great, thank you!