让计时器使用Kotlin中的主线程 [英] Having A Timer Use The Main Thread in Kotlin

查看:94
本文介绍了让计时器使用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.

如何使用MainThread?

How can I get this to use the MainThread?

推荐答案

您可以扩展timerTask以在主线程上返回.基本上,获得在主线程上运行的Hander:

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
     }
});

然后让timerTask在上面的run方法中执行其功能参数.另外,您也可以在lambda中包含该代码,甚至使用 activity.runOnUiThread().真正正确的解决方案取决于您在代码中执行此操作的频率,而只需使用 runOnUiThread 即可.

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.

这篇关于让计时器使用Kotlin中的主线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆