Kotlin_协程实现计时器Timer

计时器实现如下,能实现多次计时,如:每2s回到一次 callback

kotlin 复制代码
/**
 * 计时器
 * @property timeOutCallback 计时结束回调
 * @constructor
 */
open class CommonTimer(private val timeOutCallback: (repeatIdex: Int) -> Unit) {
    /**
     * 停止计时
     */
    fun stop() {
        println("momo: call timer stop")
        stoped = true
        job?.cancel()
        job = null
    }

    /**
     * 开始计时
     * @param interval Long 计时间隔
     * @param repeatCount Int 重复次数
     */
    fun start(interval: Long, repeatCount: Int = 1) {
        if (stoped == false) { stop() }
        println("momo: call timer start")
        stoped = false
        job = CoroutineScope(Dispatchers.Default).launch {
            repeat(repeatCount) {
                delay(interval)
                CoroutineScope(Dispatchers.Main).launch {
                    timeOutCallback(it)
                }
                if (stoped) return@repeat
                if (repeatCount - 1 == it) stop()
            }
        }
        job?.start()
    }

    private var job: Job? = null
    private var stoped: Boolean = true
}

使用案例:

kotlin 复制代码
class TimerDemo : ComponentActivity() {
    private val timer = CommonTimer {
        println("momo: timer out $it")
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            Row(
                modifier = Modifier
                    .padding(all = 30.dp)
                    .fillMaxWidth()
                    .height(44.dp),
                horizontalArrangement = Arrangement.SpaceEvenly,
            ) {
                Text(text = "开始计时", modifier = Modifier.clickable {
                    println("momo: click start")
                    timer.start(interval = 2000, repeatCount = 3)
                })
                Text(text = "结束计时", modifier = Modifier.clickable {
                    println("momo: click stop")
                    timer.stop()
                })
            }
        }
    }
}

运行结果:

例1:点击开始后无操作:

kotlin 复制代码
momo: click start
momo: call timer start
momo: timer out 0
momo: timer out 1
momo: timer out 2

例2:点击开始后,回调2次后,点击结束

kotlin 复制代码
momo: click start
momo: call timer start
momo: timer out 0
momo: timer out 1
momo: call timer stop
momo: timer out 2

github demo

相关推荐
Lei活在当下26 分钟前
【业务场景架构实战】8. 订单状态流转在 UI 端的呈现设计
android·设计模式·架构
小趴菜822739 分钟前
Android中加载unity aar包实现方案
android·unity·游戏引擎
qq_2529241943 分钟前
PHP 8.0+ 现代Web开发实战指南 引
android·前端·php
Jeled43 分钟前
Android 本地存储方案深度解析:SharedPreferences、DataStore、MMKV 全面对比
android·前端·缓存·kotlin·android studio·android jetpack
宝杰X73 小时前
Compose Multiplatform+Kotlin Multiplatfrom 第七弹跨平台 AI开源
人工智能·开源·kotlin
2501_915918417 小时前
掌握 iOS 26 App 运行状况,多工具协作下的监控策略
android·ios·小程序·https·uni-app·iphone·webview
寒山李白8 小时前
关于Java项目构建/配置工具方式(Gradle-Groovy、Gradle-Kotlin、Maven)的区别于选择
java·kotlin·gradle·maven
2501_9159090610 小时前
iOS 混淆实战,多工具组合完成 IPA 混淆与加固(源码 + 成品 + 运维一体化方案)
android·运维·ios·小程序·uni-app·iphone·webview
*才华有限公司*11 小时前
安卓前后端连接教程
android