使用RxJava在不同的线程上进行领域,网络操作,订阅和观察 [英] Realm, network operations, subscribing and observing on different threads with RxJava
问题描述
我需要:
- 在后台线程上从API获取一些数据
- 在用户界面上显示数据
-
保存到领域.
- 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
我有4个标签可同时提取不同的消息.
I have 4 tabs fetching different messages at the same time.
fetchItemsFromServer()是一个密集的调用,并且将此调用限制在一个线程中是不好的.我需要这种灵活性.
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?
大多数示例都倾向于将重点放在从Realm获取与使用网络操作上:
Most examples e.g tend to be focused on fetching from Realm vs working with network operations:
以下示例:
Rxjava- https://realm.io/news/realm-java-0.87 .0/
在RxJava中使用领域- https://realm.io/news/using- realm-with-rxjava/(以前的解决方案,但性能方面有缺陷)
Using realm with RxJava - https://realm.io/news/using-realm-with-rxjava/ (previous solution but performance drawbacks)
My Realm由数据库模块通过依赖项注入(Dagger 2)提供
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());
}
}
推荐答案
不是在UI线程上保存数据,而是在后台使用以下模式进行操作:
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);
}
}
这篇关于使用RxJava在不同的线程上进行领域,网络操作,订阅和观察的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!