Reputation: 2053
I have this piece of code where I am observing errorMessageData and accountViewModel is viewModel with Activity scope and I am observing it in different fragments I want to be notified only once for example if in FirstFragment I get notified about errorMessageData and then I navigate to SecondFragment I don't want to be notified again or it should be true for opposite case If SecondFragment is in active state I do notified there about errorMessage change I don't want to notified in FirstFragment when I navigate there.
accountViewModel.errorMessageData.observe(viewLifecycleOwner, Observer {
message ->
message?.let { Toast.makeText(context, it, Toast.LENGTH_LONG).show() }
})
Upvotes: 0
Views: 1018
Reputation: 29260
Wrap your LiveData object in a ConsumableValue
like this
class ConsumableValue<T>(private val data: T) {
private var consumed = false
fun consume(block: ConsumableValue<T>.(T) -> Unit) {
if (!consumed) {
consumed = true
block(data)
}
}
}
then in viewmodel
val foo = MutableLiveData<Consumable<Foo>>()
and in your fragment
viewModel.foo.observe(this, Observer { consumable ->
consumable.consume {
TODO()
}
})
Upvotes: 4