我正在使用suspendCoroutine
来避免在Dialog
s中使用回调。但是,在Android Dialog
s中,当对话框被解除时(通过单击对话框区域外部),没有明显的地方可以调用Continuation.resume()
。如果您在Dialog.setOnDismissListener()
中尝试调用,则必须跟踪是否已在按钮侦听器中调用了resume。
suspend fun displayDialog() = suspendCoroutine<String?> { continuation ->
val builder = AlertDialog.Builder(context)
builder.setCancelable(true)
builder.setNegativeButton(android.R.string.cancel) { _, _ ->
continuation.resume(null)
}
builder.setPositiveButton(android.R.string.ok) { _, _ ->
continuation.resume("it's ok")
}
val dialog = builder.show()
dialog.setOnDismissListener {
// if the user clicked on OK, then resume has already been called
// and we get an IllegalStateException
continuation.resume(null)
}
}
那么,跟踪是否已经调用了简历(以避免第二次调用它),或者只是不打扰resume(null)
调用(在onDismissListener中)是否更好?
Continuation是一个低级原语,应该只恢复一次,所以你必须跟踪resume
在使用时是否已被调用。或者,您可以使用更高级别的通信原语,例如CompletableDeferred
,它具有多用途的complete
函数:
suspend fun displayDialog(): String? {
val deferred = CompletableDeferred<String?>()
val builder = AlertDialog.Builder(context)
builder.setCancelable(true)
builder.setNegativeButton(android.R.string.cancel) { _, _ ->
deferred.complete(null)
}
builder.setPositiveButton(android.R.string.ok) { _, _ ->
deferred.complete("it's ok")
}
val dialog = builder.show()
dialog.setOnDismissListener {
deferred.complete(null)
}
return deferred.await()
}