前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Kotlin_协程实现计时器Timer

Kotlin_协程实现计时器Timer

作者头像
mikimo
发布2024-06-25 14:57:04
900
发布2024-06-25 14:57:04
举报
文章被收录于专栏:iOS开发~iOS开发~

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

代码语言:javascript
复制
/**
 * 计时器
 * @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
}

使用案例:

代码语言:javascript
复制
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:点击开始后无操作:

代码语言:javascript
复制
momo: click start
momo: call timer start
momo: timer out 0
momo: timer out 1
momo: timer out 2

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

代码语言:javascript
复制
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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2024-06-24,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档