计时器 Timer(Kotlin Flow)

代码: 

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
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值