Realm.getInstance(context) rarely returns an already closed instance. How is this possible?
I am using Realm with RxJava, for https://realm.io/news/using-realm-with-rxjava/
In particular, this method throws an IllegalStateException: This Realm instance has already been closed, making it unusable.
@Override public void call(final Subscriber<? super RealmList<T>> subscriber) { final Realm realm = Realm.getInstance(context); subscriber.add(Subscriptions.create(new Action0() { @Override public void call() { try { realm.close(); } catch (RealmException ex) { subscriber.onError(ex); } } })); RealmList<T> object; realm.beginTransaction();
If I comment on the problem realm.close(); , no problem. Although I think this will lead to a memory leak from memory.
My best guess as to why this happens is that multiple calls to this method are made, and if these calls to the methods line up perfectly, can an instance of an already closed state be restored?
EDIT: using Schedulers.io() , I get many warnings Calling close() on a Realm that is already closed . I assume that after I have finished using the .io() stream, the region instance automatically closes. Not sure why this will happen.
EDIT2: By switching to using Schedulers.newThread() instead of Schedulers.io() for my observables, the problem stopped appearing. But I see many warnings Remember to call close() on all Realm instances . I am sure that I am closing them, so I am very confused about this.
EDIT3: Switching to using AndroidSchedulers.mainThread() , no errors. Also, my Realm calls are triggered on the main thread, which is bad bad. My guess why this does not raise any warnings is that realm now lives in the main thread, which is also called by realm.close() (via rx.subscriber ).
EDIT4: Here is the logic of observing my kingdom.
@Override public Observable<List<ImageArticleCategoryEntity>> getArticleBuckets() { return RealmObservable.list(context, GET_ARTICLE_BUCKETS) .filter(FILTER_OUT_NULL_OR_EMPTY_LIST) .switchIfEmpty(refreshAndSaveAndLoadNewDataFromDb) .map(CONVERT_FROM_REALMLIST_TO_IMAGE_ARTICLE_ENTITYLIST); } public void loadArticleImages() { articleRepo.getArticleBuckets() .subscribeOn(RealmThread.get()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<List<ImageArticleCategoryEntity>>() { @Override public void onCompleted() { Timber.v("Loading article images complete!"); if (view != null) view.hideLoadingAnimation(); } @Override public void onError(Throwable e) { Timber.e("Error loading article images", e); Log.e("tag", "Error loading article images", e); if (view != null) { view.hideLoadingAnimation(); view.showLoadingErrorToast(); } } @Override public void onNext(List<ImageArticleCategoryEntity> integerImageArticleCategoryEntityHashMap) { if (view != null) view.loadArticleImages(integerImageArticleCategoryEntityHashMap); } });