作为标题,在Kotlin中是否有方法在延迟(例如1秒)后调用函数?


当前回答

我使用以下函数:

fun <T> delayedAsyncTask(delayMs: Long = 0, task: () -> T): ScheduledFuture<T> {
    return Executors
        .newSingleThreadScheduledExecutor()
        .schedule(Callable<T> { task() }, delayMs, TimeUnit.MILLISECONDS)
}

fun <T> asyncTask(task: () -> T) = delayedAsyncTask(0, task)

这是一个延迟函数的单元测试。当然,使用返回的将来是可选的。

    @Test
    fun `delayed task work correctly`() {
        val future = delayedAsyncTask(1000) {
            "lambda returns hello world"
        }
        assertEquals(false, future.isDone)
        Thread.sleep(1100)
        assertEquals(true, future.isDone)
        assertEquals("lambda returns hello world", future.get())
    }

其他回答

如果你在一个带有viewModel作用域的片段中,你可以使用Kotlin协程:

    myViewModel.viewModelScope.launch {
        delay(2000)
        // DoSomething()
    }

如果你正在使用最新的Android api, Handler空构造函数已经被弃用,你应该包括一个循环程序。你可以很容易地通过loop . getmainlooper()得到一个。

    Handler(Looper.getMainLooper()).postDelayed({
        //Your code
    }, 2000) //millis

我建议使用kotlin协程,如果你想取消它。它结构简单,重量轻。

fun repeatFun(): Job {
    return coroutineScope.launch {  
        while(isActive) {
            //do your work here
            delay(1000)
        }
    }
}

//start the loop
val repeatFun = repeatRequest()

//Cancel the loop
repeatFun.cancel()
val timer = Timer()
timer.schedule(timerTask { nextScreen() }, 3000)

一个简单的例子来展示3秒后的祝酒词:

fun onBtnClick() {
    val handler = Handler()
    handler.postDelayed({ showToast() }, 3000)
}

fun showToast(){
    Toast.makeText(context, "Its toast!", Toast.LENGTH_SHORT).show()
}