rxjava realmdb caching code example
Example: rxjava realmdb caching
Realm realm;
RealmResults<Task> liveResults;
public void start() {
realm = Realm.getDefaultInstance();
reloadTasks();
}
public void reloadTasks() {
if(liveResults != null && liveResults.isValid()) {
liveResults.removeChangeListener(this);
}
dataLoading.set(true);
liveResults = getFilteredResults(realm);
liveResults.addChangeListener(this);
}
public void stop() {
liveResults.removeChangeListener(this);
liveResults = null;
realm.close();
}
private RealmResults<Task> getFilteredResults(Realm realm) {
switch(selectedFilter) {
case ALL_TASKS:
return tasksRepository.getTasks(realm);
case ACTIVE_TASKS:
return tasksRepository.getActiveTasks(realm);
case COMPLETED_TASKS:
return tasksRepository.getCompletedTasks(realm);
default:
throw new IllegalArgumentException("Invalid filter type [" + selectedFilter + "]");
}
}
@Override
public void onChanged(RealmResults<Task> tasks) {
if(!tasks.isLoaded()) {
return;
}
notifyPropertyChanged(BR.empty);
dataLoading.set(false);
updateUi(tasks);
}