Search code examples
androidkotlintimercountdowntimer

Android Kotlin how kill a timer or countdowntimer fast?


The problem: if I smash the button, I ended up with multiple timers.

lateinit var timer1: CountDownTimer
    ...
    Button(onClick = {
               timer1 = object: CountDownTimer(20000000, 1000) {
                           override fun onTick(millisUntilFinished: Long) {
                                    Log.d("mytagtt","timer")
                           }
    
                            override fun onFinish() {
                                    TODO("Not yet implemented")
                              }
                        }.start()
             }){ Text("starttimer") }

Canceling the old one doesn't make things any better. I think the problem is, that the object is no more assigned to the variable and therefor the timer doesn't respond to timer1.cancel().

How can I solve this problem. The timer needs to run in background so launcheffect doesn't work for me.


Solution

  • Replace your Button() with:

    Button(onClick = {
                   if (::timer1.isInitialized) timer1.cancel()
    
                   timer1 = object: CountDownTimer(20000000, 1000) {
                               override fun onTick(millisUntilFinished: Long) {
                                        Log.d("mytagtt","timer")
                               }
        
                                override fun onFinish() {
                                        TODO("Not yet implemented")
                                  }
                            }.start()
                 }){ Text("starttimer") }
    

    This is ugly — using .isInitialized is a "code smell" IMHO — but it is the simplest solution within the confines of the code in your question.

    Why do you think countdowntimer is not the right thing?

    Partly because it has never been the right solution IMHO. It was something that they tossed into Android 1.0 and have kept around for backwards compatibility reasons, but it never really worked all that well given other Android architecture aspects, such as configuration changes.

    Partly because you wrote "The timer needs to run in background so launcheffect doesn't work for me", and CountDownTimer is not well-suited for many background scenarios.