spierce7
09/26/2020, 8:41 PMFlow
, what’s the best way to call something when the context it’s running in is cancelled? i.e. when the flow is cancelled, I need to call `process.destroy()`:
actual fun run(command: String): Flow<String> = flow {
val split = command.split(' ')
val process = ProcessBuilder(split).apply {
redirectErrorStream(true)
}.start()
process.inputStream.source().use { processSource ->
processSource.buffer().use { bufferedProcessSource ->
while (true) {
val line = bufferedProcessSource.readUtf8Line() ?: break
emit(line)
}
}
}
}.flowOn(<http://Dispatchers.IO|Dispatchers.IO>)
bezrukov
09/26/2020, 8:50 PMcurrentCoroutineContext
from flow {}
for checking if it still activebezrukov
09/26/2020, 8:53 PMwhile(true)
to while (currentCoroutineContext().isActive)
. Also, I believe emit
will throw cancellation exception if flow's collector was cancelled (since 1.3.7). Then you can call process.destroy()
in finally blockbezrukov
09/26/2020, 8:54 PMspierce7
09/27/2020, 3:33 AMspierce7
09/27/2020, 3:33 AMcurrentCoroutineContext()
and coroutineContext
? It doesn’t look like itspierce7
09/27/2020, 3:34 AMbezrukov
09/27/2020, 2:16 PMthis
(e.g. if you write flow { }
inside `coroutineScope`/`launch`/`async` etc or if you write the flow operator as an extension function of CoroutineScope, or something like that). There is an example in the link I mentioned where coroutineContext will refer to the wrong context.