Last active
February 20, 2019 23:22
-
-
Save nschwermann/c4aaabb1b99fe7199c03def5cd51c300 to your computer and use it in GitHub Desktop.
CoroutineDialog
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
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>() | |
} | |
} |
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
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