Kotlin 流 倒计时

    fun countDownCoroutines(
        total: Int,
        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(viewModelScope)
    }
countDownCoroutines(60, onTick = { second ->
                                        setCountDown(second)
                                    }, onFinish = {
                                        setCountDown(0)
                                    })

onTick就是返回当前秒数

你可能感兴趣的:(#,038Compose,kotlin,android,开发语言)