Implementing An Infinite Event Loop


#1

Have implemented an infinite event loop in Kotlin like this:

import kotlinx.coroutines.experimental.runBlocking

private const val PRINT_STR_ITEM = 1
private const val EXIT_ITEM = 2

fun main(args: Array<String>) = runBlocking {
    var evtLoopRunning = true

    while (evtLoopRunning) {
        println("-- Menu --")
        println("1. Print String")
        println("2. Exit")
        print("\nEnter number: ")
        evtLoopRunning = handleMenuInput()
    }
}

private fun printString() {
    var str = ""

    while (str.isEmpty()) {
        print("\nEnter String to print: ")
        str = readLine() ?: ""
        if (str.isNotEmpty()) println("You entered the following String: $str")
    }
}

private fun handleMenuInput() = when (readLine()) {
    PRINT_STR_ITEM.toString() -> {
        printString()
        true
    }
    EXIT_ITEM.toString() -> false
    else -> true
}

Not sure if the above implementation is low CPU usage. Seems to be using a low amount of CPU when looking at what is happening via Gnome System Monitor. What is the best way to implement an infinite event loop? Are Kotlin Coroutines designed to handle event loops?


#2

Because you use readLine(), this code performs fine. readLine() does not busy-wait, so it does not consume CPU cycles. The thread is put to sleep until an event (e.g. a key press) occurs.

In this case, your loop looks fine. There is no problem with using a thread to wait for user input. Unless you have to build a system that needs to wait for the input of thousands of users.

Coroutines would be needless overkill for this situation as coroutines were designed to make asynchronous code more readable. There is no asynchronous code here.