Is there a way to launch a coroutine that 'listens...
# coroutines
a
Is there a way to launch a coroutine that 'listens' to stdin input while the rest of the program runs? something like
launch { while(true) { //listen to keyboard input and do stuff } }
j
what about:``` /** * Create a listener for stdin [System.in] and return a channel through which all user inputs lines are sent. * * (One element in the channel = one line entered by the user) * * Closing the channel would end the listener */ fun createStdindListener(): ReceiveChannel<String> = produce { System.
in
.bufferedReader() .useLines { lines -> lines.forEach { send(it) } } } ```
Here is a more generic implementation and how to use it:
Copy code
fun InputStream.openReadChannel(): ReceiveChannel<String> = produce {
  bufferedReader()
      .useLines { lines ->
        lines.forEach { send(it) }
      }
}

fun main(args: Array<String>) {
  val inputChannel = System.`in`.openReadChannel()
  
  val printJob = launch {
    println("Start to listen on inputs")
    inputChannel.consumeEach { println("User entered: $it") }
    println("Stop to listen on inputs")
  }

  runBlocking {
    delay(10, TimeUnit.SECONDS)

    inputChannel.cancel()

    printJob.join()
  }
}
👍 1