0

I used the lifecycle callback onCreate to fetch data like below

  mWeOutViewModel.getPlaceListLiveData()
            .observe(this, weOutItemViewModels -> {
                AppLogger.i(getCustomTag() + "adding items " + weOutItemViewModels.size());
                if (weOutItemViewModels != null && weOutItemViewModels.size() > 0)
                    mWeOutListAdapter.addToExisting(weOutItemViewModels);

            });

As you can see the AppLogger output the initial size which is 0 when the fragment is displayed, then I fetch the data and call postValue (setValue crashes the app and it expected because I fetch data from the internet using a background thread). So I call post value like below :

 private void updatePlaces(List<WeOutGroupedViewModels> weOutGroupedViewModels) {
    List<WeOutGroupedViewModels> oldList = placeMutableLiveData.getValue();
    oldList.addAll(weOutGroupedViewModels);
    AppLogger.i(TAG +" updating places "+oldList.size());
    placeMutableLiveData.postValue(oldList);
}

As you can see the other AppLogger before postValue, the size of the list is displayed(not empty), but nothing happens until the app crashes and nothing is shown in the logs. I have no ways of debugging since even on debug mode nothing happens. The post value doesn't trigger the observer.

I initialize the mutableLivedata like this :

    private final MutableLiveData<List<WeOutGroupedViewModels>> placeMutableLiveData = new MutableLiveData<>();

and access like this :

public LiveData<List<WeOutGroupedViewModels>> getPlaceListLiveData() {
    return placeMutableLiveData;
}

Event when I make the livedata public to access directly the livedata, there is no change (just in case someone thinks that's is where the issue comes from)

TheLetch
  • 375
  • 1
  • 4
  • 15

1 Answers1

0

Instead of placeMutableLiveData.postValue(oldList);

I recommend using

placeMutableLiveData.postValue(Collections.unmodifiableList(new ArrayList<>(newList));

That way, the next time you access this list, you won't be able to mutate it in place, which is a good thing. You're not supposed to mutate the list inside a reactive state holder (MutableLiveData).

So theoretically it should look like this:

private void updatePlaces(List<WeOutGroupedViewModels> weOutGroupedViewModels) {
    List<WeOutGroupedViewModels> newList = new ArrayList<>(placeMutableLiveData.getValue());
    
    newList.addAll(weOutGroupedViewModels);
    AppLogger.i(TAG +" updating places "+newList.size());
    placeMutableLiveData.postValue(Collections.unmodifiableList(newList));
}
EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428