Search code examples
kotlinhandlerlooper

Kotlin Immediate execute postDelayed


On specific events I want to stop a handler. I want a target to fade after several seconds. I want to interrupt and immediately fade (or extend time before fading how can I do this? What is the new best practice for accomplishing this? Here is existing code:

    private fun startTargetFade(target: Target, delayMs: Long = 2000) {
        Handler(Looper.getMainLooper()).postDelayed({
            target.isVisible = false
            viewModel.remove(target)
        }, delayMs)
    }

Solution

  • I use CountDownTimer not a looper. I created a class that contains both the CountDownTimer and Target. When I want to do something to the Target based on the CountDownTimer, I find the instance containing the timer, I know its sibling, the Target is the object I need to act on.

    val countDownTimer = object : CountDownTimer(wadeTime, 1000) {
                            override fun onTick(millisUntilFinished: Long) {}
                            override fun onFinish() {}
    

    if I want to end early is call:

    countDownTimer.cancel()