Android实现计时器
网上的方案大多用的是Executor和Handler,写法不是很简便,用Kotlin实现一个也很简单
private var countTimeJob: Job? = null
fun resetCountTime(
time: Int,
timeUnit: TimeUnit,
onTick: (Long) -> Unit,
onFinish: () -> Unit
) {
countTimeJob?.cancel()
countTimeJob = viewModelScope.launch {
var remainingTime = timeUnit.toMillis(time.toLong())
while (remainingTime > 0L) {
onTick(remainingTime)
delay(1000)
remainingTime -= 1000
}
onFinish()
}
}