Is there any simple way I can read from stdin with...
# announcements
p
Is there any simple way I can read from stdin without blocking? Maybe something like
Copy code
readStuff {
    println(it)
}
// Do other things meanwhile...
k
Copy code
fun readStuff(block: (String?) -> Unit) {
    async {
        while(true) {
            val line = readLine()
            if (line == "exit") break
            block(line)
        }
    }
}

fun main(args: Array<String>) {
    readStuff {
        println(it)
    }

    // do other stuff
}
p
Nice, ty 👍
g
Much better to use
launch
instead of async in this case, otherwise you hide possible exceptions inside of async (because newer call
await
) and you actually don't need result, so launch is enough. Also it's not good to block thread from default dispatcher of coroutines, so would be better to create a special CoroutineContext for this case Also such coroutine is not cancellable (no suspension points), so you can use isActive instead of true in while or call yeld after line read And if you don't care about cancellation you can just use common thread in this case:
thread { readLine() }
, no coroutine features used in this example
p
Yeah, I am just using thread lol. I didn't feel like enabling coro support.
g
Actually, with coroutines one can write very convenient non-blocking version of readLine (with support of iterable, non-blocking and cancellable)
p
Probably. I don't need something complicated for this at all, and I'm going to move it to a GUI at some point as well. For now
thread { while(true) { doThings(readLine()!!) } }
should be fine for my purposes.