https://kotlinlang.org logo
#multiplatform
Title
# multiplatform
s

spierce7

11/18/2021, 3:44 PM
I’m seeing a strange issue with coroutines inside of
Flow
. I’m performing a blocking call on a coroutine thread (Using Dispatchers.IO), and because of that, even though the Collecting flow is finished, the cancellation logic (killing a process in this case), doesn’t happen for a good while after:
Copy code
try {
    while (currentCoroutineContext().isActive && process.isAlive) {
        val line = bufferedProcessSource.readUtf8Line() ?: break
        emit(line)
    }
} catch (e: CancellationException) {
    throw e
} finally {
    if (process.isAlive) {
        println("C$id - Destroying Process")
        process.destroy()
    }
}
If I change the
bufferedProcessSource.readUtf8Line()
line to below, it fixes it, but it’s very ugly. Is there a better way to fix it?
Copy code
@Suppress("RedundantAsync")
val line = CoroutineScope(currentCoroutineContext())
    .async(<http://Dispatchers.IO|Dispatchers.IO>) { bufferedProcessSource.readUtf8Line() }
    .await()
    ?: break
If I use
withContext(<http://Dispatchers.IO|Dispatchers.IO>)
it doesn’t fix it, because I’m already using
<http://Dispatchers.IO|Dispatchers.IO>
, so the same thread is re-used.
3 Views