I'm using suspendCoroutine to avoid using callbacks in Dialogs. However, in Android Dialogs there is no obvious place to call Continuation.resume() when the dialog is dismissed (by clicking outside of the dialog area). If you attempt the call in Dialog.setOnDismissListener() then you have to keep track of whether resume was already called in the button listener.
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)
}
}
So, is it better to keep track of whether resume was already called (to avoid calling it a second time), or just don't bother with the resume(null) call (in onDismissListener)?
Continuation is a low-level primitive that shall be resumed exactly once, so you have to track whether resume was already called when using it. Alternatively, you can use higher-level communication primitives, for example CompletableDeferred, which has multi-use complete function:
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()
}