perryprog
03/27/2018, 5:11 PMreadStuff {
println(it)
}
// Do other things meanwhile...
kristofdho
03/27/2018, 5:35 PMfun 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
}
perryprog
03/27/2018, 5:35 PMgildor
03/28/2018, 12:34 AMlaunch
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 exampleperryprog
03/28/2018, 12:35 AMgildor
03/28/2018, 12:39 AMperryprog
03/28/2018, 12:41 AMthread { while(true) { doThings(readLine()!!) } }
should be fine for my purposes.