Multiple instances of Livedata observers

Viewed 6010

I am struggling to find a solution for calling a livedata observer multiple times in one activity and not creating multiple instances of it, this leads to the problem when the database changes I got callbacks from all the instances.

ViewModel

public class RatingsViewModel extends AndroidViewModel {

private RatingsRepository ratingsRepository;
private LiveData<List<Rating>> ratingsList;

public RatingsViewModel(Application application) {
    super(application);
    ratingsRepository = new RatingsRepository(application);

}

public LiveData<List<Rating>> getRatingsByDate(LocalDate date) {
    ratingsList = ratingsRepository.getActivitiesByDate(date);
    return ratingsList;
}

Activity

private void getRatingsByDate(LocalDate date) {
    ratingsViewModel.getRatingsByDate(date).observe(this, activities -> {
        // list populating stuff
    });
}

I tried calling hasObserver() but it returns false so I cannot remove the observers.

1 Answers

You should be able to do something like following (in Kotlin but should be easily translatable in to Java if needed)

val dateLiveData: MutableLiveData<Date> = MutableLiveData()

val ratingsList = MediatorLiveData<List<Rating>>().apply {
    this.addSource(dateLiveData) {
        this.value = ratingsRepository.getActivitiesByDate(dateLiveData.value)
    }
}

fun setDate(date: Date) {
    dateLiveData.value = date
}

You'd call observe from onCreate() for example in your activity/fragment and then call setDate() when that value changes.

Related