Last active
December 30, 2020 09:25
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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