首先定义流
用来显示ui
private val _lockedTillSecond = MutableStateFlow(0L)
val lockedTillSecond: StateFlow<Long> = _lockedTillSecond
private var countdownJob: Job? = null
定义job 来防止重复的倒计时。
fun startCountdown() {
// 取消之前的倒计时
countdownJob?.cancel()
// 创建一个倒计时流
val countdownFlow: Flow<Long> = flow {
var remainingTime = _lockedTillSecond.value
while (true) {
emit(remainingTime)
delay(1000)
remainingTime--
}
}.takeWhile { it > 0 }
// 收集倒计时流,并更新 lockedTillSecond
countdownJob = viewModelScope.launch {
countdownFlow.collect { remainingTime ->
// LL.e(TAG, "倒计时 ${remainingTime}")
updateLockedTill(remainingTime)
// 当倒计时剩余1秒时,调用 refresh() 方法
if (remainingTime == 1L) {
refresh()
}
}
}
}
在compose 使用的时候
val currentTime by viewModel.lockedTillSecond.collectAsState(0L)