如何通过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()
}
相关推荐
淡淡的香烟14 小时前
AndroidAI使用心得
android
chjif15 小时前
Android 设备管控开发实战:无障碍如何准确识别当前前台 App?
android
chjif15 小时前
Android 设备管控开发实战:企业受控终端的 DNS 域名策略实现
android·华为·harmonyos
c2385617 小时前
MySQL 基础用法(下):查询进阶与核心特性
android·c语言·c++·mysql
math_hongfan17 小时前
鸿蒙Agent高级技能自定义开发:自定义意图服务/能力注册/Agent技能编排/服务插件开发实战
android·学习·华为·harmonyos·鸿蒙
2501_9151063218 小时前
iOS 证书类型及作用说明 账号证书与签名配置的完整解读
android·ios·小程序·https·uni-app·iphone·webview
九皇叔叔18 小时前
RHEL9 安装 MySQL 8.4.11.LTS 版本
android·mysql·adb
海兰19 小时前
【数据库】tdsql(MySQL )的事务隔离级别
android·数据库·mysql
哆啦A梦z19 小时前
Android BLE 实战:从小米手环 7 踩坑到完整连接框架
android
IKUN家族19 小时前
KMP全栈开发:从Android到AI Agent的技术演进与实践
android·人工智能