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?
I think you're just looking for
read more
I think this could be way an easier solution:
If you need some explainations, just tell me and I will implement it :)
PS: if I missunderstood your question, let me know!
First of all you can't have
boolean
return type if you want to do your transaction asynchronously. You will have to use eitherInterface
pass result back to caller or you have to opt for some other means like RxJava.just to give you example.
The RxJava way(As this would be simplest way):
You subscribe the returned
Flowable
on desired thread/schedular to perform transaction on that particular thread.