Last active
August 27, 2019 15:26
-
-
Save alz-ahm/4cf607a76569436123f18fddb16fe5da to your computer and use it in GitHub Desktop.
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
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