本文介绍了使用来自不同线程的领域事务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有我经常使用的writeToRealm方法.我需要从不同的线程使用它并削减样板代码.有什么更好的方法来完成此任务?
I have writeToRealm method that I use very often. And I need to use it from different threads and cut boilerplate code. What is the better way for this task?
private boolean writeToRealm(String user, String id) {
SubscriberObject subscriber = new SubscriberObject();
if(mRealm.where(SubscriberObject.class)
.equalTo(SubscriberObject.ID,id).findAll().isEmpty()
&&mRealm.where(SubscriberObject.class)
.equalTo(SubscriberObject.USERNAME,user).findAll().isEmpty()) {
subscriber.setId(id);
subscriber.setUsername(user);
mRealm.beginTransaction();
mRealm.insert(subscriber);
mRealm.commitTransaction();
return true;
}
return false;
}
我计划在下面使用构造(或类似的东西),但是我无法创建正确的构造:
I am planning to use construction below (or something like this) but I can't create a correct construction:
public static Boolean writeToRealm(final String user,final String id){
Realm mRealm;
return Flowable.using(
mRealm = Realm.getDefaultInstance(),
new Function<Realm, Boolean>() {
@Override
public Boolean apply(@NonNull Realm realm) throws Exception {
SubscriberObject subscriber = new SubscriberObject();
if(realm.where(SubscriberObject.class)
.equalTo(SubscriberObject.ID,id).findAll().isEmpty()
&&realm.where(SubscriberObject.class)
.equalTo(SubscriberObject.USERNAME,user).findAll().isEmpty()) {
subscriber.setId(id);
subscriber.setUsername(user);
realm.beginTransaction();
realm.insert(subscriber);
realm.commitTransaction();
return true;
}
return false;
}
},
mRealm.close()).subscribeOn(Schedulers.io());
}
或者我是否需要为此任务创建带有循环程序的线程类?
Or may be I need to create a thread class with looper for this task?
如何更好地将此方法和类似方法集成到干净的体系结构中?
How to better integrate this method and similar methods into a clean architecture?
推荐答案
我认为您只是在寻找
private boolean writeToRealm(String user, String id) {
try(Realm realm = Realm.getDefaultInstance()) {
if(realm.where(SubscriberObject.class).equalTo(SubscriberObject.ID,id).count() <= 0L
&& realm.where(SubscriberObject.class).equalTo(SubscriberObject.USERNAME,user).count() <= 0L) {
final SubscriberObject subscriber = new SubscriberObject();
subscriber.setId(id);
subscriber.setUsername(user);
realm.executeTransaction(r -> r.insert(subscriber));
return true;
}
}
return false;
}
这篇关于使用来自不同线程的领域事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!