`withContext` doc string says > Calls the speci...
# coroutines
d
withContext
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
Copy code
inputStream.bufferedReader().use { reader ->
            reader.readLine()?.split(",")?.map { it.trim() } ?: emptyList()
        }
k
withContext
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 io
d
Yes, my assumption, however, is that the
bufferReader.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.
that is, it may suspend directly on the
withContext
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 that
r
Since these Java methods are blocking and not suspending, and they are mainly IO-bound, wrapping the whole block in a
withContext
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>
.
d
I apologize, but won't the "thread" doing IO-bound work block? Will there be any real context switching during the IO? My understanding of
<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.
d
right, i think that's what i was saying
r
So yes, these Java functions will still block the thread. There's nothing you can do about that. What you can do is put the blocking calls on a "spare" thread that expects to be blocked, rather than a "core" thread that is in `Dispatchers.Default`'s relatively small pool of
n
threads (where
n
is the number of CPU cores on the machine)
1
d
Yes, gotcha. bc my app is IO bound, I set the dispatcher to IO at the highest level possible already 🙂 so I assume all the
withContext
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.