Countdown can be said to be a common requirement of Android development, the previous implementation is generally the following schemes
- The handler + postDelayed () method
- The Timer + TimerTask + Handler mode is used
- ScheduledExecutorService + Handler mode
- RxJava way
- CountDownTimer way
Now, with coroutines and Flow, we can use the Flow tool to implement this requirement more elegantly.
- Rely on the import
api 'org. Jetbrains. Kotlinx: kotlinx coroutines -- core: 1.4.2'
api 'org. Jetbrains. Kotlinx: kotlinx coroutines - android: 1.4.1'
// lifecycleScope(optional)
api "Androidx. Lifecycle: lifecycle - runtime - KTX: 2.2.0." "
Copy the code
- Code implementation
fun countDownCoroutines(total:Int,onTick:(Int) - >Unit,onFinish:()->Unit,
scope: CoroutineScope = GlobalScope):Job{
return flow{
for (i in total downTo 0){
emit(i)
delay(1000)
}
}.flowOn(Dispatchers.Default)
.onCompletion { onFinish.invoke() }
.onEach { onTick.invoke(it) }
.flowOn(Dispatchers.Main)
.launchIn(scope)
}
Copy the code
The CoroutineScope uses GlobalScope by default. Considering memory leaks, lifecycleScope is recommended to better realize lifecycle management and avoid memory leaks.
The Demo address