Reputation: 12300
I use Realm.getDefaultInstance() in a worker thread (in a service) and save my records with:
Realm realm = Realm.getDefaultInstance();
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
...
realm.copyToRealmOrUpdate(...
When done (this is sync, so it is done right away), I submit an EventBus message to the UI thread that it can start the next task.
The UI thread calls to a different worker thread again which does another Realm.getDefaultInstance() and then a findAll() call. It finds nothing. Why is this? "Some time later" it will find the items fine, but not right away.
The items are in the database already: If I do the findAll() right after saving the items on the first worker thread, it does return the items. If I do it AFTER that again on the second worker thread it finds nothing. Is this some kind of caching?
Upvotes: 2
Views: 96
Reputation: 12300
The problem was based on me using a threadpool, on which threads the Realm instance was not updated. A solution for me is to not use the threadpool, so instead of
observable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
I now use this everywhere:
observable
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
And it solves all Realm threading problems. It is a little less efficient probably, but fine for my purpose.
Upvotes: 1