Skip to content

Instantly share code, notes, and snippets.

@addeeandra
Last active January 31, 2021 15:43
Show Gist options
  • Save addeeandra/5cafbbd00646393276c2b89856c11bdc to your computer and use it in GitHub Desktop.
Save addeeandra/5cafbbd00646393276c2b89856c11bdc to your computer and use it in GitHub Desktop.
ViewModel SingleLiveEvent - Wraps the MutableLiveData<ActionEvent<T>>
class Event<out T>(private val content: T) {
var hasBeenUsed = false
private set
fun getContentIfNotUsed(): T? {
return if (hasBeenUsed) {
null
} else {
hasBeenUsed = true
content
}
}
fun peekContent(): T = content
}
open class LiveEvent<T> {
val action: MutableLiveData<ActionEvent<T>> = MutableLiveData()
fun observe(lifecycleOwner: LifecycleOwner, callback: (data: T) -> Unit) {
action.observe(lifecycleOwner, Observer {
action.value?.let {
if (!it.hasBeenUsed) {
callback(it.getContentIfNotUsed() ?: it.peekContent())
}
}
})
}
}
fun <T> SingleEvent<T>.post(value: T) {
this.action.postValue(Event(value))
}
fun SingleEvent<Unit>.post() {
this.action.postValue(Event(Unit))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment