Skip to content

Instantly share code, notes, and snippets.

@DanteAndroid
Created March 29, 2021 07:19
Show Gist options
  • Save DanteAndroid/874eede76a7672d35142ef130249c09a to your computer and use it in GitHub Desktop.
Save DanteAndroid/874eede76a7672d35142ef130249c09a to your computer and use it in GitHub Desktop.
One-time event wrapper for LiveData
package com.rrtv.utils
/**
* Used as a wrapper for data that is exposed via a LiveData that represents an event.
*/
open class Event<out T>(private val content: T) {
var hasBeenHandled = false
private set
/**
* Returns the content and prevents its use again.
*/
fun getContentIfNotHandled(): T? {
return if (hasBeenHandled) null else {
hasBeenHandled = true
content
}
}
/**
* Returns the content, even if it's already been handled.
*/
fun peekContent(): T = content
}
@DanteAndroid
Copy link
Author

DanteAndroid commented Mar 29, 2021

Usage:

class SomeViewModel constructor(private val repository: Repository) {

        val message: MutableLiveData<Event<String>> = MutableLiveData()

        fun someMethod(){
        // do net request
        message.value = Event("Your hint message here")
    }

}

And observe message in your view:

        vm.message.observe(this, Observer { data ->
            data.getContentIfNotHandled()?.let {
                // show your message
            }
        })

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment