Thread
#multiplatform
    spierce7

    spierce7

    10 months ago
    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:
    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?
    @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.