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?