如何通过Kotlin协程, 简化"连续依次弹窗(Dialog队列)"的需求

效果预览

代码预览

kotlin 复制代码
lifecycleScope.launch {
    showDialog("签到活动", "签到领10000币") // 直到dialog被关闭, 才会继续运行下一行
    showDialog("新手任务", "做任务领20000币") // 直到dialog被关闭, 才会继续运行下一行
    showDialog("首充奖励", "首充6元送神装")
}

代码实现

要做到上一个showDialig()在关闭时才继续运行下一个函数,需要用到协程挂起的特性, 然后在 OnDismiss()回调中将协程恢复, 为了将这种基于回调的方法包装成协程挂起函数, 可以使用suspendCancellableCoroutine函数

kotlin 复制代码
suspend fun showDialog(title: String, content: String) = suspendCancellableCoroutine { continuation ->
    MaterialAlertDialogBuilder(this)
        .setTitle(title)
        .setMessage(content)
        .setPositiveButton("我知道了") { dialog, which ->
            dialog.dismiss()
        }
        .setOnDismissListener {
            continuation.resume(Unit)
        }
        .show()
}
相关推荐
一航jason1 分钟前
Android平台推理框架及试用场景模型对比
android·人工智能·ai·架构·ai编程·llama
一航jason9 分钟前
Android 端侧大模型推理框架对比
android·人工智能·ai·ai编程·llama·ai-native
新时代牛马33 分钟前
cyclictest 毛刺从哪来?从ftrace、latencytop、perf到IRQ/调度延迟定位
android·开发语言·python·kotlin
光电的一只菜鸡3 小时前
为什么调整LSC会对AF产生影响
android·开发语言·kotlin
凛_Lin~~3 小时前
LiveData 源码解析
android·安卓·livedata
hai_android3 小时前
FusibleFlow:Kotlin Flow 的融合机制原理
android·kotlin
龚寿生3 小时前
23-敏捷开发实战:从Scrum到看板的团队协作方法论
android·学习·scrum·敏捷流程
zhangguojia75 小时前
Activity启动流程(四):从setContentView到View树创建与Window挂载
android
三少爷的鞋7 小时前
Kotlin 2026:裁员、AI、Rust——黄金时代结束了吗?Jake Wharton 为你解答
android