如何通过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()
}
相关推荐
mygljx2 小时前
MySQL 数据库连接池爆满问题排查与解决
android·数据库·mysql
xinhuanjieyi3 小时前
ruoyimate导入sql\antflow\bpm_init_db.sql报错
android·数据库·sql
闲猫5 小时前
基于RABC的权限控制设计
android
星霜笔记8 小时前
GitMob — 手机端 GitHub 管理工具
android·kotlin·github·android jetpack
LiuYaoheng8 小时前
问题记录:Android Studio Low memory
android·ide·android studio
独隅9 小时前
Python 标准库 (Standard Library) 全面使用指南
android·开发语言·python
always_TT9 小时前
strlen、strcpy、strcat等常用字符串函数
android
qqty12179 小时前
MySQL Workbench菜单汉化为中文
android·数据库·mysql
2401_895521349 小时前
MySQL中between and的基本用法
android·数据库·mysql
云云鬼才10 小时前
CoCo编辑器、图形化编程怎么调用Scheme(跳转应用)
android