I am trying to create a Flow api for `java.lang.Pr...
# coroutines
y
I am trying to create a Flow api for
java.lang.Process
and although this does NOT trigger an error, the call to
waitFor
is flagged as inaprorriate blocking call. Is there a better way to do it? Code in thread to not pollute here...
This is the code...
Copy code
sealed class ProcessResult {
    data class Out(val line: String) : ProcessResult()
    data class Err(val line: String) : ProcessResult()
    data class ExitValue(val exitValue: Int) : ProcessResult()
}

@OptIn(ExperimentalCoroutinesApi::class)
fun Process.asFlow(charset: Charset = Charsets.UTF_8) : Flow<ProcessResult> {
    val process = this
    return channelFlow {

        coroutineScope {
            if(process.inputStream != null) {
                launch(<http://Dispatchers.IO|Dispatchers.IO>) {
                    process.inputStream.use {
                        for(line in it.bufferedReader(charset).lines()) {
                            send(ProcessResult.Out(line))
                        }
                    }
                }
            }

            if(process.errorStream != null) {
                launch(<http://Dispatchers.IO|Dispatchers.IO>) {
                    process.errorStream.use {
                        for(line in it.bufferedReader(charset).lines()) {
                            send(ProcessResult.Err(line))
                        }
                    }
                }
            }
        }

        send(ProcessResult.ExitValue(process.waitFor()))

    }
}
e
Use
onExit().await()
y
getting
Unresolved reference: await
I needed to add
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-jdk8:1.5.0")
to my build file. It now works. Thanks!
I now have a similar issue (inappropriate blocking call) when trying to start the process inside a suspend function:
ProcessBuilder.start()
gets flagged as inappropriate blocking call.
e
Just suppress this one. However, it would be still prudent to do it inside
withContext(<http://Dispatchers.IO|Dispatchers.IO>) { ... }just in case
y
ok thanks