如何通过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()
}
相关推荐
CS_Zero14 小时前
安卓开发:Linux的android工具命令
android·linux·运维
fellow9914 小时前
DSH Desktop - Android Edition
android·agent·deepseek·harness·dsh
Carson带你学Android14 小时前
Android Studio Rabbit 2 发布:除了Gemini,40+ AI Agent 正式入驻!
android·ai编程
三少爷的鞋1 天前
Java 线程自上而下,Kotlin 协程自下而上
android
好的佩奇1 天前
Dart 之增强枚举
android·flutter·dart
梦影_1 天前
MySQL进阶教程(五)—— SQL调优(下)
android·大数据·数据库·后端·sql·mysql·database
好的佩奇1 天前
蓝牙之无线电与通信距离
android·flutter·蓝牙
vilya1 天前
我把一套完整的 Python Agent 运行时塞进手机 APK:依赖闭包、Rust 轮子和三个真机坑
android
呆呆敲代码的小Y1 天前
【实战精选面试题】C# 面试题详细解答,按难易程度排序
android·java·游戏·c#·游戏开发·unity面试题·c#面试题
思想觉悟1 天前
SEAndroid实战
android·linux·c++