https://kotlinlang.org logo
#coroutines
Title
# coroutines
n

Norbi

04/28/2021, 11:53 AM
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

Zach Klippenstein (he/him) [MOD]

04/28/2021, 2:19 PM
asInputStream
doesn’t call
runBlocking
though,
read
does.
u

uli

04/28/2021, 2:23 PM
Could you go for callback-based or future-based instead of blocking?
🤔 1
n

Norbi

04/28/2021, 2:59 PM
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

Zach Klippenstein (he/him) [MOD]

04/28/2021, 3:06 PM
You can’t, but you can add documentation that says hey there’s a suspending version of this function, use that instead
7 Views