Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Navigation Component - Problem with Livedata lifecycle

I'm beginning with navigation components and I'm facing some problem with a livedata observer.

For example: I have this livedata, who manage auth response from server.

viewModel.authenticate.observe(this, Observer {
        manageAuthResponse(it)
        })

Everything works fine, and I go to Fragment B. But when I'm in Fragment B, and I try to go back to Fragment A (who contains that livedata), the Observer fires again with the previous result (SUCCESS).

How can I prevent this?

When I go back, I want to refresh this result and prevent livedata observer to be fired.

like image 217
LMaker Avatar asked Jan 27 '26 02:01

LMaker


1 Answers

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 authenticate = MutableLiveData<Consumable<AuthenticationObject>>()

and in your fragment

viewModel.authenticate.observe(this, Observer { consumable ->
        consumable.consume {
            manageAuthResponse(it)
        }
    })
like image 198
Francesc Avatar answered Jan 28 '26 17:01

Francesc