如何通过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()
}
相关推荐
2501_9159214316 分钟前
只有 IPA 没有源码时,如何给 iOS 应用做安全处理
android·安全·ios·小程序·uni-app·iphone·webview
恋猫de小郭17 分钟前
Flutter 3.41 iOS 键盘负优化:一个代码洁癖引发的负优化
android·前端·flutter
榴月子29 分钟前
Mac 安装 Homebrew、 Java 和 Kotlin
java·macos·kotlin
十六年开源服务商40 分钟前
2026年WordPress网站安全检测服务避坑指南
android·安全
一直向钱1 小时前
android stutio 安装Ai插件写代码
android
linchare1 小时前
[原创]如何排查php-fpm的502报错(SIGSEGV)
android
XiaoLeisj2 小时前
Android 权限管理实战:运行时申请、ActivityResultLauncher 与设置页授权
android·java·权限
橙子199110162 小时前
Android 中的权限申请
android
2501_915921432 小时前
iOS APP上架工具,在没有 Mac 的环境中发布苹果应用
android·macos·ios·小程序·uni-app·iphone·webview
范特西林2 小时前
第一篇:从电源键到上帝进程——硬件觉醒与 Init 的诞生
android