Android 倒计时一般方式:

    • Handler 方式
    • CountDownTimer 方式
    • RxJava 方式

    上述倒计时方式实现省略,这里使用 kotlin 的 flow 实现:

    1. fun countDownCoroutines(
    2. total: Int,
    3. scope: CoroutineScope,
    4. onTick: (Int) -> Unit,
    5. onStart: (() -> Unit)? = null,
    6. onFinish: (() -> Unit)? = null,
    7. ): Job {
    8. return flow {
    9. for (i in total downTo 0) {
    10. emit(i)
    11. delay(1000)
    12. }
    13. }.flowOn(Dispatchers.Main)
    14. .onStart { onStart?.invoke() }
    15. .onCompletion { onFinish?.invoke() }
    16. .onEach { onTick.invoke(it) }
    17. .launchIn(scope)
    18. }

    使用:

    1. private var mCountdownJob: Job? = null
    2. mBinding.btnStart.setOnClickListener {
    3. mCountdownJob = countDownCoroutines(60, lifecycleScope,
    4. onTick = { second ->
    5. mBinding.text.text = "${second}s后重发"
    6. }, onStart = {
    7. // countdown start
    8. }, onFinish = {
    9. // countdown finished, reset state
    10. mBinding.text.text = "发送验证码"
    11. })
    12. }
    13. mBinding.btnStop.setOnClickListener {
    14. // cancel countdown
    15. mCountdownJob?.cancel()
    16. }