https://kotlinlang.org logo
#coroutines
Title
# coroutines
y

Yan Pujante

05/14/2021, 5:28 PM
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

elizarov

05/14/2021, 7:00 PM
Use
onExit().await()
y

Yan Pujante

05/14/2021, 7:02 PM
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

elizarov

05/15/2021, 5:38 PM
Just suppress this one. However, it would be still prudent to do it inside
withContext(<http://Dispatchers.IO|Dispatchers.IO>) { ... }just in case
y

Yan Pujante

05/15/2021, 5:39 PM
ok thanks
12 Views