Skip to content

Instantly share code, notes, and snippets.

@alz-ahm
Last active August 27, 2019 15:26
Show Gist options
  • Save alz-ahm/4cf607a76569436123f18fddb16fe5da to your computer and use it in GitHub Desktop.
Save alz-ahm/4cf607a76569436123f18fddb16fe5da to your computer and use it in GitHub Desktop.
open class Event<out T>(private val content: T) {
var hasBeenHandled = false
private set // Allow external read but not write
/**
* Returns the content and prevents its use again.
*/
fun getContentIfNotHandledOrReturnNull(): T? {
return if (hasBeenHandled) {
null
} else {
hasBeenHandled = true
content
}
}
/**
* Returns the content, even if it's already been handled.
*/
fun peekContent(): T = content
}
class MyViewModel() : ViewModel(){
val networkError = MutableLiveData<Event<String>>()
}
viewModel.networkError.observe(this, Observer { event ->
event?.getContentIfNotHandledOrReturnNull()?.let {
showToast(it)
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment