Android.如何实现片段内的倒计时计时器?



我试图在片段内实现简单的倒计时计时器(没有视图模型或用例)。下面是我的代码:

private fun startTimer(totalSeconds: Int): Flow<Int> =
(totalSeconds - 1 downTo 0)
.asFlow() 
.onEach { delay(1000) } 
.onStart { emit(totalSeconds) } 
.conflate() 
.transform { remainingSeconds: Int ->
emit(remainingSeconds)
}

onCreate(savedInstanceState: Bundle?)内部:

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
TestTimerTheme {
val scope = rememberCoroutineScope()
lifecycleScope.launchWhenResumed {
scope.launch {
startTimer(60)
.collect {
Log.d("MY_TAG", "sec = $it") // THIS is called many times for second
mutableState.emit(it)
}
}
}
val state = mutableState.collectAsState()
CustomTimer(state.value)
}
}
}

结果,流随机发出值。也就是说,不是每秒发射一个事件,而是多个事件。请告诉我需要在我的代码中修复什么,以便计时器工作正常,并且每秒只给出一次值。

请尝试以下定时器功能:

fun startTimer(totalSeconds: Int): Flow<Int> = flow {
var seconds = totalSeconds
do {
emit(seconds)
delay(1000)
seconds -= 1
} while (seconds >= 0)
}

最新更新