我有一个函数,该函数创建带有用户名列表的alertDialog,并且我想从alertDialog返回选定的用户名作为函数的输出。我使用协程来包装回调。
问题在于代码没有等待用户从AlertDialog中选择用户名。
如何让代码等待用户从AlertDialog中选择用户名?
suspend fun showUserSelectionDialog(usersAndEmails: Map<String, String>) : String? = suspendCancellableCoroutine { cont ->
val users: Array<String> = usersAndEmails.keys.toTypedArray()
val builder = AlertDialog.Builder(activity)
builder.setTitle("Select your username")
.setItems(users) { _, which ->
val username = users[which]
cont.resume(usersAndEmails[username])
}
.setCancelable(true)
.setOnCancelListener {
cont.resume(null)
}
val dialog: AlertDialog = builder.create()
dialog.show()
}
GlobalScope.launch(Dispatchers.Main) {
var username: String? = userSelector.showUserSelectionDialog(usernamesAndEmails)
}
谢谢!