Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having A Timer Use The Main Thread in Kotlin

Tags:

android

kotlin

I have an operation that needs to be delayed for a few seconds. I am using the scheduler and timer like so:

import java.util.Timer
import kotlin.concurrent.timerTask

 val timer = Timer()
        sliderLastAdjusted = System.currentTimeMillis()

        timer.schedule(timerTask {
            val newTime = System.currentTimeMillis()
            val elapsedTime = newTime - sliderLastAdjusted

            if (elapsedTime > 2000) {

                masterViewModel.updateLeagueProjections()
            }
        }, 2000)

While this works for executing a command with a delayed time and prevents other commands within the same time period from executing, it does use the main thread - which causes an issue when updating observables.

How can I get this to use the MainThread?

like image 615
Devin Dixon Avatar asked Dec 21 '25 21:12

Devin Dixon


1 Answers

You can use an Handler which when declared from the Main Thread(eg. in the Activity) will be attached to it,

You could try this :

val delayedHandler = Handler()
delayedHandler.postDelayed({
//// Your Code
}, 2000)

Or you can also keep your Timer, simply declare a Handler outside the timer, and use the Handler post() Method from your Timer

like image 95
User One Avatar answered Dec 24 '25 11:12

User One



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!