代码:
- class FlowTimer(
- private val duration: Int,
- private val scope: CoroutineScope,
- private val onTick: (Int) -> Unit,
- private val onStart: (() -> Unit)? = null,
- private val onFinish: (() -> Unit)? = null,
- private val interval: Int = 1
- ) {
-
- private val id = System.currentTimeMillis()
-
- fun start(): Job {
- if (duration <= 0 || interval <= 0) {
- throw IllegalArgumentException("duration or interval cannot less than zero")
- }
- return flow {
- for (i in duration downTo 0) {
- emit(i)
- delay((interval * 1000).toLong())
- }
- }.onStart { onStart?.invoke() }
- .onCompletion {
- if (it == null) {
- onFinish?.invoke()
- }
- }
- .onEach { onTick.invoke(it) }
- .flowOn(Dispatchers.Main) // 确保上游回调,是在主线程回调
- .launchIn(scope)
- }
-
- override fun toString(): String = "Timer:(id=${id}"
- }
-
用法:
- private var mTimer: Job? = null
-
- override fun onCreate(savedInstanceState: Bundle?) {
- mTimer = FlowTimer(duration, lifecycleScope,
- onTick = { sec ->
- Log.d("MainActivity", "sec:${sec}")
- },
- onFinish = { }
- ).start()
- }
-
- override fun onDestroy() {
- mTimer?.cancel
- }