I have a question related to coroutines and blocki...
# coroutines
n
I have a question related to coroutines and blocking IO integration. For integrating with a blocking library, I need a conversion similar to this:
Copy code
// This is my asynchronous/suspending input stream
interface AsyncInputStream {
    // This method has semantics similar to InputStream.read() but suspends instead of blocking
    suspend fun read(): Int
}

fun AsyncInputStream.asInputStream() = object : java.io.InputStream() {
    override fun read(): Int {
        return runBlocking { this@asInputStream.read() } // Is runBlocking() correct here?
    }
}
If I understand correctly, using
runBlocking
is incorrect because it "should not be used from a coroutine", and
AsyncInputStream.asInputStream()
would possibly be called from coroutines. Thanks.
z
asInputStream
doesn’t call
runBlocking
though,
read
does.
u
Could you go for callback-based or future-based instead of blocking?
🤔 1
n
asInputStream
doesn’t call
runBlocking
though
Yes... although this is a general problem: in case of a non-suspend function how could I know that it won't be "used from a coroutine"?
z
You can’t, but you can add documentation that says hey there’s a suspending version of this function, use that instead