当前位置: 首页 > article >正文

计时器 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
}


http://www.kler.cn/news/136877.html

相关文章:

  • 华为云产品介绍
  • HttpOnly Cookie
  • ReactOS系统中平衡二叉树,在一个空间中寻找与给定地址范围重合或部分重合的(已分配)区间
  • uniapp使用uviewPlus的up-upload上传文件的UI但是自己使用axios进行文件上传
  • ARM/Linux嵌入式面经(五二):华为
  • vue中选项式 API(Options API) 和 组合式 API(Composition API)区别
  • Active Directory 和域名系统(DNS)的相互关系
  • 串口工作流程硬核解析,没有比这更简单的了!
  • html常用的标签
  • 【前端知识】Node——http模块url模块的常用操作
  • IP地理位置定位技术:保护网络安全的新利器
  • meterpreter命令
  • js 深度学习(七)
  • Java高级编程-----网络编程
  • 效率提升利器:Automa插件的实用指南
  • 大数据基础设施搭建 - Kafka(with ZooKeeper)
  • clickhouse 业务日志告警
  • excel-gen.js 导出excel 功能
  • 源码安装Apache
  • 【Linux专题】退出bash后再运行jobs命令为什么不会显示后台任务
  • springMVC学习笔记-请求映射,参数绑定,响应,restful,响应状态码,springMVC拦截器
  • CentOS 7 安装CMake指定版本3.21.2
  • 数据库备份
  • 竞赛 题目:基于深度学习的中文汉字识别 - 深度学习 卷积神经网络 机器视觉 OCR
  • 算法(圆的定义和相关术语)
  • 运动装备经营小程序商城效果如何