App uses RxJava to make network call, then modify results with data from database and display them. App listens to database changes with android.database.ContentObserver and modify data when there is change. Currently it works with code below but is there some nicer RX way how to achieve same? Thanks!
Observable<ArrayList<Foo>> observable = Observable.create(new Observable.OnSubscribe<ArrayList<Foo>>() {
@Override
public void call(Subscriber<? super ArrayList<Foo>> subscriber) {
//make api call and get list of foos
ArrayList<Foo> apiResults = api.getFooList();
//loop results and if foo is already in local sqlite db, update it with local values
for (Foo foo : apiResults) {
if(localSqlite.contains(foo){
foo.update(localSqlite.get(foo));
}
}
subscriber.onNext(apiResults);
HandlerThread observerThread = new HandlerThread("ContentObserver-thread");
observerThread.start();
final ContentObserver co = new ContentObserver(new Handler(observerThread.getLooper())) {
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
for (Foo foo : apiResults) {
if(localSqlite.contains(foo){
foo.update(localSqlite.get(foo));
}
subscriber.onNext(apiResults);
}
mContext.getContentResolver().registerContentObserver(uri, true, co);
subscriber.add(Subscriptions.create(new Action0() {
@Override
public void call() {
mContext.getContentResolver().unregisterContentObserver(co);
}
}));
}
Subscription subscription = observable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(subscriber);