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

相关推荐
geovindu12 小时前
sql:Search-Optimized SQL Queries using mysql 9.0
android·数据库·sql·mysql·数据库开发·数据库架构
知之则吱吱14 小时前
Android 开发者验证机制迎来新变化:核心要求、实施时间与开发者应对指南
android·google
墨天梦15 小时前
D09_Retrofit接口与数据转换
android·kotlin·retrofit
电商API_1800790524716 小时前
闲鱼商品列表API接口商品详情API接口请求示例(含一份真实响应数据示例)
android·数据挖掘·网络爬虫·跨境电商·反向海淘
我命由我1234516 小时前
Android 广播 - 组件通信
android·java·开发语言·android studio·android jetpack·android-studio·android runtime
阿俊-全栈开发16 小时前
LikeShop 单商户标准版商品管理二开:分类、SKU 规格与库存联动实现
android·likeshop·likeshop开源商城
用户21816970493019 小时前
Kotlin 语法二
android
妖星19 小时前
android 源码分析surfaceFinger是如何通过设置属性启动bootanim
android
JoyMonitor19 小时前
APK mmap 内存增长定位:pagemap 与 DEX 结构联合定位方法
android