如何通过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()
}
相关推荐
杉氧40 分钟前
React 灵魂:深入剖析 Hooks 与副作用(Side Effects)陷阱
android·前端·react native
又见情义1 小时前
RK3568 + RTL8211F 网络唤醒(WOL)功能适配全记录
android·网络·驱动开发
用户0934077735142 小时前
HarmonyOS WPS Open SDK 实践:registerApp 鉴权与就绪门禁
android·typescript·harmonyos
jike_20262 小时前
会议离线录音APP:无网络记录能力对比
android·智能手机·语音识别
always_TT3 小时前
【Python 字符串格式化:format() 方法】
android·开发语言·python
恋猫de小郭3 小时前
AI 时代,一个优化 Flutter 的重复代码工具 Deslop
android·前端·flutter
RisunJan3 小时前
Android 面试知识点整理
android·面试·职场和发展
脚踏实地,坚持不懈!4 小时前
Android ANR 内核底层全解析:从一次触摸到“应用无响应”
android·linux
xhBruce4 小时前
强制使用桌面模式 - SECONDARY_HOME -android-15.0.0_r23
android·launcher3
_祝你今天愉快15 小时前
从驱动来分析服务的添加过程
android