Live Data is getting called multiple times? Live Data is getting called multiple times? android android

Live Data is getting called multiple times?


The role of the ViewModel is to represent the current state of the view. LiveData adds the ability to observe state changes. You are treating your LiveData object as a way to carry the response back upon a call to authenticate. Instead, your authenticate method should simply take the credentials as parameters, decide whether or not to log the person in, and if you do, update the LiveData ViewModel to reflect that the person is logged in, then observers will get this and most likely dismiss this view and show whatever other parts of the authenticated state you want to show (e.g. LoggedInUsername).

So in summary:

  • make a class called CurrentAuthenticatedSession or something, with for instance a username field, and have that be null to begin with
  • when the authentication call is made, verify look up the user info
  • if it's current update the LiveData instance of your CurrentAuthenticatedSession
  • have the 'currentlyLoggedInUser' field be listening for updates to this object
  • set the text of that control to the value of the field username

That's one way. Because a login screen is transient, observers of state updates may be seen as superfluous. But that's how the ViewModel/LiveData mechanism works.


My answer is not a solution to this question description but rather to question title. Just title.

Originally answered here

If your observer for a LiveData<*> is getting called multiple times then it means you are calling livedata.observe(...) multiple times. This happened to me as I was doing livedata.observe(...) in a method and was calling this method whenever user does some action thus observing liveData again. To solve this I moved livedata.observe(...) to onCreate() lifecycle method.

What was the scenario?The App has a color swatch. When user selects a color I had to make API call to fetch Product Images for that color. So was making API call and was observing livedata in onColorChanged() . When user selects a new color, onColorChanged() would be called again thus observing for livedata changes again.