Don Mitchell
06/18/2025, 6:02 PMwithContext
doc string says
Calls the specified suspending block with a given coroutine context, suspends until it completes, and returns the result.which sounds like it auto implements a callback pattern, but I doubt it. I ask bc copilot implies that I can wrap java file io methods in
withContext
to get it to do the filesystem request and then suspend while waiting for the OS. example non-suspending call which I'd like to suspend
inputStream.bufferedReader().use { reader ->
reader.readLine()?.split(",")?.map { it.trim() } ?: emptyList()
}
kevin.cianfarini
06/18/2025, 6:29 PMwithContext
will switch the execution context and then yes, will essentially wait for a callback. That doesn't automatically make io nonblocking, though. The callback would be from another thread which is blocked on ioDon Mitchell
06/18/2025, 8:08 PMbufferReader.use
will block once it starts rather than getting the wished for context swap after it makes the file io request until the OS hands it the first block of the file.Don Mitchell
06/18/2025, 8:09 PMwithContext
call but it won't have initiated the file io; so, when it swaps back in, it will still need to do the file io and will block on thatrkechols
06/18/2025, 8:26 PMwithContext
that uses <http://Dispatchers.IO|Dispatchers.IO>
is a good idea.
This will allow your calling thread to suspend (and go do other work) while the IO-bound work (mostly waiting) is performed on a thread managed by <http://Dispatchers.IO|Dispatchers.IO>
.Don Mitchell
06/18/2025, 8:34 PM<http://Dispatchers.IO|Dispatchers.IO>
is that it provides a default configurable 64 contexts which expect frequent interruptions but it doesn't really know anything about IO nor when to do the switching any differently than the other Dispatchers
which is just on suspend, withContext, delay, launch, async, ...
not on any low level impls.rkechols
06/18/2025, 8:35 PMDon Mitchell
06/18/2025, 8:35 PMrkechols
06/18/2025, 8:38 PMn
threads (where n
is the number of CPU cores on the machine)Don Mitchell
06/18/2025, 8:40 PMwithContext
will do is give the coroutine manager permission to swap contexts but it won't increase throughput by never leaving the cpu waiting for IO.