I.S
I.S

Reputation: 2053

How can I be notified only once of liveData change in different Fragments?

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

Answers (1)

Francesc
Francesc

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

Related Questions