1

I have been facing issues while using live data and shared view model as a medium to interact between my fragments and activity. Here is the issue..

Activity A (Has a view model X shared across two fragments)
---Displays----> Fragment A on startup (dashboard type of view) --- on select in A (viewmodel updated)--> Live data Triggered

--view model X in the activity observes changes and adds Fragment B dynamically to the back stack--> Fragment B is active now.

Couple of issues, that I'm facing

  1. I see that, on back press from fragment B, back to Fragment A and vice versa, the previous value of the livedata is observed at the beginning before fetching the latest data.

  2. On rotation/ state change, my activity observes for the fragment changes the second time ( kind of same as above)

Any workaround for this ? or is there anything that i'm missing

Thanks in advance..

  • Could you show the code that you are using to observe in Activity A and the variable in ViewModel X? – NhatVM Apr 26 '21 at 02:47
  • Variable X initialised as MutableLiveData and populated by using set Value after data is received. Observing in activity as x.getVariable.observe(this, onChanged -> {}) – Fareed khan Apr 26 '21 at 04:55
  • It is no so clear. But I guest you are having a variable like this in ViewModel: var isOpenB = MutableLiveData(). And you update this variable by passing true or false. Right? – NhatVM Apr 26 '21 at 06:54
  • Yea... Not a Boolean actually, a custom object that I require for further usage – Fareed khan Apr 26 '21 at 07:23
  • short answer for you : When the configuration change or when you back from another page, LiveData will push the data to your fragment again. To give the change one time, you can refer the answer in there: https://stackoverflow.com/questions/56071990/android-architecture-singleliveevent-and-eventobserver-practicle-example-in-java – NhatVM Apr 26 '21 at 07:51
  • In some cases, you need to use a "feature" (aka: hack) from the Architecture Samples provided by google. In short, if you want an event to be delivered only once, you can use the [single live event](https://github.com/android/architecture-samples/blob/dev-todo-mvvm-live/todoapp/app/src/main/java/com/example/android/architecture/blueprints/todoapp/SingleLiveEvent.java) implementation so the event is only sent once per "emission/value". – Martin Marconcini Apr 26 '21 at 09:12
  • Thanks Martin and NhatVM will refer these – Fareed khan Apr 26 '21 at 09:49

1 Answers1

1

as a quick workaround I went with this approach wherein I observe my changes only if my viewLifeCycleOwner is in a resumed state.

getViewLifeCycleOwner().getCurrentState() == Lifecycle.State.RESUMED. Ideally it should be a single event approach, but yea for a quick fix this should work.