Inappropriate blocking method call output stream write

Solution 1:

In general if there is a truly async alternative, it better suits the coroutines model. You could find callback-based APIs and wrap them into suspend functions using suspendCoroutine or suspendCancellableCoroutine.

However, more often than not, you need to deal with actual blocking IO.

In that case, the easiest is to simply run the blocking IO on the IO dispatcher using withContext(Dispatchers.IO):

suspend fun write(byteArray: ByteArray) = withContext(Dispatchers.IO) {    
    bos.write(byteArray)
}

However, you have to think about which level you're using the IO dispatcher at. If this method is quite low-level, maybe you should use withContext higher in the call stack, and just keep this method non-suspend.

Solution 2:

OutputStream.write is a blocking function, and by convention suspend functions must never block. You can wrap it in withContext so it uses the IO dispatcher to do it appropriately. However, it is possible this won't make the warning go away because the Kotlin lint is kind of buggy about false positives for this issue.

suspend fun write(byteArray: ByteArray) = withContext(Dispatchers.IO) {    
    bos.write(byteArray)
}