如何通过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()
}
相关推荐
M0066881 天前
低代码平台使用留存的技术基础与系统设计逻辑
android·rxjava
nono牛1 天前
深入理解gatekeeperd 与 android.hardware.gatekeeper@1.0-service调用规则
android
lxysbly1 天前
红白机模拟器安卓版带金手指
android
·云扬·1 天前
【实操教程】Excel文件转CSV并导入MySQL的完整步骤
android·mysql·excel
触想工业平板电脑一体机1 天前
【触想智能】工业触控一体机在船舶海运设备上应用的特点和具体场景分析
android·网络·计算机外设·电脑·智能电视
Change_JW1 天前
reserved mem addr & size
android
汤面不加鱼丸1 天前
android实践:生成.9.png图片
android
叶羽西1 天前
下载Android源代码
android
nono牛1 天前
android.hardware.gatekeeper@1.0-service 与 gatekeeperd 区别
android
&岁月不待人&1 天前
⏺ Android 录屏缩放异常排查:Pixel 3 XL 上的完美风暴
android