gpt4 book ai didi

multithreading - 如何将Retrofit 2与Realm和RxJava结合

转载 作者:行者123 更新时间:2023-12-03 12:52:01 25 4
gpt4 key购买 nike

我想将对 Realm 的改造响应保存在后台线程中,然后将其传递给UI线程,但这有点棘手,因为Realm对线程非常敏感。因此代码看起来像这样,请将您的修改提交给所有更好的解决方案:)

restApi.userRealmList()
.doOnNext(userRealmModels -> {
if (userRealmModels != null){
mRealm = Realm.getInstance(mContext);
mRealm.asObservable()
.map(realm -> mRealm.copyToRealmOrUpdate(userEntity))
.subscribe(new Subscriber<Object>() {
@Override
public void onCompleted() {

}

@Override
public void onError(Throwable e) {
e.printStackTrace();
}

@Override
public void onNext(Object o) {
Log.d("RealmManager", "user added!");
}
});
}})
.map(userEntityDataMapper::transformAll)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<List<User>>() {
@Override
public void onCompleted() {
hideViewLoading();
}

@Override
public void onError(Throwable e) {
hideViewLoading();
showErrorMessage(new DefaultErrorBundle((Exception) e));
showViewRetry();
}

@Override
public void onNext(List<User> users) {
showUsersCollectionInView(users);
}
});

最佳答案

您的代码看起来不像可以编译吗?例如。什么是userEntity。另外,您的copyToRealmOrUpdate不在事务内,因此也会崩溃,但与线程无关。

如果要在将某些数据发送到UI之前将其另存为副作用,则应该能够执行以下操作:

restApi.userRealmList()
.doOnNext(userRealmModels -> {
if (userRealmModels != null) {
Realm realm = Realm.getInstance(mContext);
realm.beginTransaction();
realm.copyToRealmOrUpdate(userRealmModels);
realm.commitTransaction();
realm.close();
}})
.map(userEntityDataMapper::transformAll)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<List<User>>() {
@Override
public void onCompleted() {
hideViewLoading();
}

@Override
public void onError(Throwable e) {
hideViewLoading();
showErrorMessage(new DefaultErrorBundle((Exception) e));
showViewRetry();
}

@Override
public void onNext(List<User> users) {
showUsersCollectionInView(users);
}
});

关于multithreading - 如何将Retrofit 2与Realm和RxJava结合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35897737/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com