Kotlin_协程实现计时器Timer

2024-06-25 14:57:04 浏览数 (4)

计时器实现如下,能实现多次计时,如:每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

0 人点赞