Ricky Gideon
Ricky Gideon

Reputation: 47

Global variable for object CountDownTimer

So I made a countdown timer using

object : CountDownTimer(waktu.toLong(), 1000)

Now I need to make a variable to cancel this countdowntimer like this

var timer = object : CountDownTimer(waktu.toLong(), 1000)

The problem now is I cannot access this variable from another function. My question is how to make a global variable for this object:countdowntimer in kotlin. I'm not sure about the variable type that I should make. Thank you

Upvotes: 0

Views: 1165

Answers (2)

Ved
Ved

Reputation: 522

you can use companion object to access your object from your desired location.

for more information, you can refer to this

create property for timer

companion object {
    lateinit var timer: CountDownTimer
}

Initialize the property and start

timer = object : CountDownTimer(YOUR_MAX_VALUE, 1000) {
        override fun onFinish() {
        // perform task on finish
        }
        override fun onTick(countdownTick: Long) {
        // perfrom tick event 
        }
    }.start()

And cancel timer when the task is finish OR activity/fragment destroyed.

override fun onBackPressed() {
super.onBackPressed()
timer.cancel()

}

to avoid memory leaks.

Upvotes: 4

Jaymin
Jaymin

Reputation: 2912

Kotlin provides the companion object expression to deal with the global variable.

You can do it like this.

companion object {
        var timer : CountDownTimer ? = null
    }

Initialize timer in your utils class or activity.

timer = object : CountDownTimer(Long.MAX_VALUE, 1000) {
                                override fun onFinish() {
                                    // Cancel the timer
                                }

                                override fun onTick(millisUntilFinished: Long) {
                                    // Handle your tick event
                                }
                            }

And start your timer

timer?.start()

Upvotes: 0

Related Questions