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

独自空忆成欢 提交于 2019-12-09 07:18:03

问题


I need to :

  • Fetch some data from an API on a background thread
  • Display the data on the UI
  • Save to Realm.

    fetchItemsFromServer().subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<ItemList>() {
        @Override
        public void call(ItemList items) {
    
            displayItems(items);
    
            try {
                realm.beginTransaction();
                realm.copyToRealmOrUpdate(itemList);
                realm.commitTransaction();
                Logger.v("Realm ", "Copied list object to realm");
            } catch (Exception e) {
                Logger.e("Realm Something went wrong ", e);
                realm.cancelTransaction();
            }
    
        }
    }
    

This throws an error : realm accessed from incorrect thread

I have 4 tabs fetching different messages at the same time.

fetchItemsFromServer() is an intensive call and confining this call to one thread is not good. I need this flexibility.

Has anyone found any workarounds using realm this way?

Most examples e.g tend to be focused on fetching from Realm vs working with network operations:

Example below:

Rxjava - https://realm.io/news/realm-java-0.87.0/

Using realm with RxJava - https://realm.io/news/using-realm-with-rxjava/ (previous solution but performance drawbacks)

My Realm is provided by a database module through dependency injection (Dagger 2)

@Module
public class DatabaseModule {

    public static final String REALM_FILE_NAME = "Realm name";

    @Provides
    Realm providesRealmInstance(Context context) {
    return Realm.getInstance(
            new RealmConfiguration.Builder(context)
                    .name(REALM_FILE_NAME)
                    .build());
    }
}

回答1:


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);
    }
}


来源:https://stackoverflow.com/questions/34800999/realm-network-operations-subscribing-and-observing-on-different-threads-with-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!