Realm, network operations, subscribing and observing on different threads with RxJava

。_饼干妹妹 提交于 2019-12-03 09:11:24

Instead of saving data on the UI thread I would do it on the background instead using the following pattern:

fetchItemsFromServer()
    .doOnNext(new Action1<ItemList>() {
        @Override
        public ItemList call(ItemList list) {
            // Save data on the background thread
            Realm realm = Realm.getDefaultInstance();
            realm.beginTransaction();
            realm.copyToRealmOrUpdate(list);
            realm.commitTransaction();
            realm.close();
        }
    })
  .subscribeOn(Schedulers.io())
  .observeOn(AndroidSchedulers.mainThread())
  .subscribe(new Action1<ItemList>() {
    @Override
    public void call(ItemList items) {
        displayItems(items);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!