I'm creating an Android app with an activity with a bottom navigation control that lets the user navigate between different fragments. In these fragments i have lists of data coming from a firebase backend that i show with a RecyclerView
.
The problem is that every time i navigate between these fragments all the data is downloaded again, while i would want to use cached data and just listen for changes.
What i have done so far is to use ViewModel
and LiveData
and they work fine. Moreover if i disconnect the phone from the Internet the data is showed (and of course is not downloaded), even if i navigate between the fragments.
In the fragment that shows the data i have:
LiveData<List<UncompletedTask>> taskLiveData = viewModel.getTaskLiveData();
taskLiveData.observe(this, new Observer<List<UncompletedTask>>() {
@Override
public void onChanged(List<UncompletedTask> uncompletedTasks) {
myAdapter.submitList(uncompletedTasks);
listener.onTodoListElementsLoaded(uncompletedTasks.size());
}
});
In the viewmodel i have:
private TodoTaskRepository repository;
@NonNull
public LiveData<List<UncompletedTask>> getTaskLiveData() {
return repository.getTaskLiveData();
}
In the TodoTaskRepository
i initialize FirebaseQueryLiveData
in the contructor and return it in getTaskLiveData()
.
Finally FirebaseQueryLiveData
is like this:
public class FirebaseQueryLiveData extends LiveData<DataSnapshot> {
private static final String LOG_TAG = "FirebaseQueryLiveData";
private final Query query;
private final MyValueEventListener listener = new MyValueEventListener();
public FirebaseQueryLiveData(Query query) {
this.query = query;
}
@Override
protected void onActive() {
query.addValueEventListener(listener);
}
@Override
protected void onInactive() {
query.removeEventListener(listener);
}
private class MyValueEventListener implements ValueEventListener {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
setValue(dataSnapshot);
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.e(LOG_TAG, "Can't listen to query " + query, databaseError.toException());
}
}
}
How can i download all the data the first time but then just listen for changes and don't download the same data while navigating between fragments if nothing is changed?