Skip to content

Instantly share code, notes, and snippets.

@0xBADDCAFE
Created May 13, 2019 07:48
Show Gist options
  • Save 0xBADDCAFE/aa4f339e8782ad92b7ee46a72deb5ed5 to your computer and use it in GitHub Desktop.
Save 0xBADDCAFE/aa4f339e8782ad92b7ee46a72deb5ed5 to your computer and use it in GitHub Desktop.
import androidx.annotation.StringRes
import androidx.appcompat.app.AlertDialog
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
class SuspensiveAlertDialogBuilder(val builder: AlertDialog.Builder) {
@StringRes
var positiveTextId: Int? = null
var positiveText: String? = null
@StringRes
var negativeTextId: Int? = null
var negativeText: String? = null
var cancelable: Boolean = true
suspend fun show() = suspendCoroutine<Boolean> { cont ->
positiveTextId?.let {
builder.setPositiveButton(it) { _, _ -> cont.resume(true) }
}
positiveText?.let {
builder.setPositiveButton(it) { _, _ -> cont.resume(true) }
}
negativeTextId?.let {
builder.setNegativeButton(it) { _, _ -> cont.resume(false) }
}
negativeText?.let {
builder.setNegativeButton(it) { _, _ -> cont.resume(false) }
}
if (cancelable) {
builder.setOnCancelListener { cont.resume(false) }
}
builder.show()
}
}
fun AlertDialog.Builder.withSuspensive() = SuspensiveAlertDialogBuilder(this)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment