• 13
name

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191

Backtrace:

File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 191
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

name Punditsdkoslkdosdkoskdo

Having A Timer Use The Main Thread in 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?

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

  • 1
Reply Report

You can extend timerTask to return on the main thread. Basically, get a Hander that runs on the main thread:

Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
     public void run() {
          // UI code goes here
     }
});

Then have timerTask execute its function parameter in the run method above. Alternatively, you can just have that code in you lambda or even use activity.runOnUiThread(). Really the correct solution comes down to how often you do this in your code, of it's a one off just use runOnUiThread.

  • 0
Reply Report

Although the previous answers are working, they are not very kotlin

Way nicer is something like this

Handler(mainLooper).post { someTextView.text = "Hello world!" }
  • 0
Reply Report