Android 倒计时一般方式:
- Handler 方式
- CountDownTimer 方式
- RxJava 方式
上述倒计时方式实现省略,这里使用 kotlin 的 flow 实现:
fun countDownCoroutines(
total: Int,
scope: CoroutineScope,
onTick: (Int) -> Unit,
onStart: (() -> Unit)? = null,
onFinish: (() -> Unit)? = null,
): Job {
return flow {
for (i in total downTo 0) {
emit(i)
delay(1000)
}
}.flowOn(Dispatchers.Main)
.onStart { onStart?.invoke() }
.onCompletion { onFinish?.invoke() }
.onEach { onTick.invoke(it) }
.launchIn(scope)
}
使用:
private var mCountdownJob: Job? = null
mBinding.btnStart.setOnClickListener {
mCountdownJob = countDownCoroutines(60, lifecycleScope,
onTick = { second ->
mBinding.text.text = "${second}s后重发"
}, onStart = {
// countdown start
}, onFinish = {
// countdown finished, reset state
mBinding.text.text = "发送验证码"
})
}
mBinding.btnStop.setOnClickListener {
// cancel countdown
mCountdownJob?.cancel()
}