Skip to content

Instantly share code, notes, and snippets.

@nschwermann
Last active February 20, 2019 23:22
Show Gist options
  • Save nschwermann/c4aaabb1b99fe7199c03def5cd51c300 to your computer and use it in GitHub Desktop.
Save nschwermann/c4aaabb1b99fe7199c03def5cd51c300 to your computer and use it in GitHub Desktop.
CoroutineDialog
abstract class CoroutineDialog<T>(context : Context, private val channel: Channel<DialogMessage<T>>) : AlertDialog(context) {
init {
setOnCancelListener {
channel.offer(DialogMessage.Cancelled)
}
}
fun positiveChannel(text : String, block : (() -> T)? = null) {
setButton(AlertDialog.BUTTON_POSITIVE, text){d, _ ->
channel.offer(DialogMessage.Positive(block?.invoke() ?: Unit as T))
d.dismiss()
}
}
fun negativeChannel(text : String) {
setButton(AlertDialog.BUTTON_NEGATIVE, text){d, _ ->
channel.offer(DialogMessage.Negative)
d.dismiss()
}
}
suspend fun showAndReceive() : DialogMessage<T>{
show()
return channel.receive()
}
sealed class DialogMessage<out T> {
class Positive<T>(val value : T) : DialogMessage<T>()
object Negative : DialogMessage<Nothing>()
object Cancelled : DialogMessage<Nothing>()
}
}
class GetCharacterDialog(context : Context, channel: Channel<CoroutineDialog.DialogMessage<String>> = Channel()) : CoroutineDialog<String>(context, channel) {
init {
val view = EditText(context).apply {
hint = "Enter Character Name"
layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
}
setView(view)
positiveChannel("Ok") {view.text.toString().trimEnd()}
negativeChannel("Cancel")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment