计时器 Timer(Kotlin Flow)

news/2023/11/30 8:12:32

代码: 

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? = nulloverride fun onCreate(savedInstanceState: Bundle?) {mTimer = FlowTimer(duration, lifecycleScope,onTick = { sec ->Log.d("MainActivity", "sec:${sec}")}, onFinish = { }).start()
}override fun onDestroy() {mTimer?.cancel
}


https://www.xjx100.cn/news/3091595.html

相关文章

基于Java GUI模拟银行自动取款机

一、课题描述 编写一个程序&#xff0c;模拟银行自动取款机的工作流程。主要功能如下所述: 当输入给定的卡号和密码&#xff08;初始卡号为888888和密码为123456)时&#xff0c;系统能登录ATM柜员机系统,用户可以按照以下规则进行: 查询余额:初始余额为50000元 ATM取款:每次…

Python-函数传参与数据类型

Python中&#xff0c;函数参数传递是通过对象的引用进行的&#xff0c;我们可以进行下面的验证。 def use_name(val):print("name id :%s" % (id(val)))val "hanshu1"print("name id modified :%s" % (id(val)))def test_ref():name "ha…

浪潮信息云峦服务器操作系统KeyarchOS体验与实践

写在前面 大家好我是网络豆&#xff0c;一名云计算运维人员&#xff0c;本文将会带大家体验一下浪潮信息服务器操作系统云峦KeyarchOS。看看浪潮信息服务器操作系统云峦KeyarchOS的优势与实践操作如何。 背景了解 KeyarchOS是浪潮信息基于Linux Kernel、OpenAnolis等开源技术…

Java 获取本地ip网卡信息

工具类 public static Optional<Inet4Address> getLocalIp4Address() throws SocketException {final List<Inet4Address> inet4Addresses getLocalIp4AddressFromNetworkInterface();if (inet4Addresses.size() ! 1) {final Optional<Inet4Address> ipBySo…

【Web】Ctfshow Nodejs刷题记录

目录 ①web334 ②web335 ③web336 ④web337 ⑤web338 ⑥web339 ⑦web340 ⑧web341 ⑨web342-343 ⑩web344 ①web334 进来是一个登录界面 下载附件&#xff0c;简单代码审计 表单传ctfshow 123456即可 ②web335 进来提示 get上传eval参数执行nodejs代码 payload: …

为什么mapper层不使用@Mapper注解,依然可以注入?

在MyBatis中&#xff0c;我们通常使用Mapper接口来操作数据库。在Spring Boot中&#xff0c;我们可以使用MapperScan注解来扫描Mapper接口所在的包&#xff0c;并将其注册到Spring容器中。但是&#xff0c;即使我们没有在Mapper接口上使用Mapper注解&#xff0c;Spring Boot也可…

nginx/html关闭网页缓存方法

【问题】 通常代理服务器默认是有缓存的&#xff0c;即用户访问网址的时候默认获取到的是缓存&#xff0c;只有刷新之后才能得到服务器端的最新文件 【解决】 以nginx为例&#xff0c;找到配置文件nginx.conf&#xff0c;找到http {}&#xff0c;在其花括号之内添加命令&…

同为科技(TOWE)智能机柜PDU助力上海华为数据中心完善机房末端配电

智能时代加速而来&#xff0c;最大的需求是算力&#xff0c;最关键的基础设施是数据中心。作为一家在信息通信领域拥有多年经验和技术积累的公司&#xff0c;华为在全国多个地区都设有数据中心&#xff0c;如知名的贵州贵安华为云全球总部、内蒙古乌兰察布华为数据中心等&#…