Kotlin是否有类似Swift的perform(#selector)与取消延迟执行机制?
Kotlin中实现Swift延迟执行+可取消的等价方案
先回顾你在Swift中的实现:
// 1. 7秒后调用showTimeoutErrorLabel perform(#selector(showTimeoutErrorLabel), with: nil, afterDelay: 7) // 2. 取消上述延迟执行操作 NSObject.cancelPreviousPerformRequests(withTarget: self) // 或精准取消指定方法 NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(showTimeoutErrorLabel), object: nil) // 目标函数 @objc func showTimeoutErrorLabel() { ... }
Kotlin里有多种方式实现类似的延迟执行+随时取消功能,以下是几种常用方案:
1. 使用Kotlin协程(推荐,跨平台/Android通用)
协程是Kotlin官方推荐的异步处理方案,实现延迟执行和取消非常简洁:
import kotlinx.coroutines.* // 保存协程Job对象,用于控制取消 private var timeoutJob: Job? = null // 启动7秒延迟执行 fun startTimeout() { // 建议使用对应生命周期的CoroutineScope,比如Android的lifecycleScope timeoutJob = CoroutineScope(Dispatchers.Main).launch { delay(7000) // 延迟7秒(单位毫秒) showTimeoutErrorLabel() } } // 取消延迟执行 fun cancelTimeout() { timeoutJob?.cancel() timeoutJob = null // 清空引用,避免内存泄漏 } // 重新调用:先取消旧任务,再启动新任务 fun restartTimeout() { cancelTimeout() startTimeout() } // 目标函数 private fun showTimeoutErrorLabel() { // 执行你的逻辑 }
2. 使用Handler(Android专属)
如果是Android环境,也可以用传统的Handler实现:
import android.os.Handler import android.os.Looper private val handler = Handler(Looper.getMainLooper()) private var timeoutRunnable: Runnable? = null // 启动延迟执行 fun startTimeout() { timeoutRunnable = Runnable { showTimeoutErrorLabel() } handler.postDelayed(timeoutRunnable!!, 7000) } // 取消延迟执行 fun cancelTimeout() { timeoutRunnable?.let { handler.removeCallbacks(it) timeoutRunnable = null } } // 重新调用 fun restartTimeout() { cancelTimeout() startTimeout() } private fun showTimeoutErrorLabel() { // 执行你的逻辑 }
3. 使用Timer和TimerTask
这种方式适合非UI线程的延迟任务,注意如果要更新UI需要切换到主线程:
import java.util.* private var timerTask: TimerTask? = null private val timer = Timer() // 启动延迟执行 fun startTimeout() { timerTask = object : TimerTask() { override fun run() { // 如果需要更新UI,Android环境下需切换到主线程 // runOnUiThread { showTimeoutErrorLabel() } showTimeoutErrorLabel() } } timer.schedule(timerTask, 7000) } // 取消延迟执行 fun cancelTimeout() { timerTask?.cancel() timerTask = null } // 重新调用 fun restartTimeout() { cancelTimeout() startTimeout() } private fun showTimeoutErrorLabel() { // 执行你的逻辑 }
内容的提问来源于stack exchange,提问作者Lance Samaria
相关产品推荐
相关产品推荐

