Interruptible countdown?

Hi, I’m trying to implement a very simple functionality: A countdown timer that counts down from 10, and if you press a button, the timer resets.

I have experience with non-interactive programming in other languages, but I don’t know even the basic patterns people use for interactive programming and I’m new to Kotlin.

Are you supposed to put everything in a while loop? e.g.

var s : Int = 10 while (s > 0) { println("$s seconds left.") s-- Thread.sleep(1) // is this the recommended way to wait in kotlin? button.setOnClickListener { s=10 } }

This seems most straightforward but I’m not sure if you need to listen for the button click every loop, since the behavior of setOnClickListener seems asynchronous (idk)? Also putting everything in one while loop is inflexible if your app has to manage many other things.

Or is it better if I solve this another way? Maybe multi-threading or coroutines? (I don’t know much about either tbh).

submitted by /u/CompulsiveContrarian
[link] [comments]