Skip to content

Instantly share code, notes, and snippets.

@Alireza-Farahani
Last active December 30, 2020 09:25
Show Gist options
  • Save Alireza-Farahani/e0bbccda31acf6d9f54a6f2d3257abda to your computer and use it in GitHub Desktop.
Save Alireza-Farahani/e0bbccda31acf6d9f54a6f2d3257abda to your computer and use it in GitHub Desktop.
Using Kotlin coroutines, you can work with AlerDialog and get result from it as if you're writing synchronous code
viewLifecycleOwner.lifecycleScope.launch {
val items = arrayOf("Foo", "Bar", "Baz")
val currentCheckedIdx = 0
val newCheckedItem = suspendCancellableCoroutine<String> { cont ->
MaterialAlertDialogBuilder(requireContext())
.setTitle(R.string.some_title)
.setSingleChoiceItems(
modesStrings,
currentCheckedIdx
) { dialog, which: Int ->
cont.resume(items[which])
dialog.dismiss()
}.setOnDismissListener {
if (cont.isActive)
cont.resume(items[currentCheckedIdx]) /*or cancel the continuation and handle the related exception*/
}.show()
}
// use newItem. e.g. persist it
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment