Soumya
Soumya

Reputation: 1420

This Realm instance has already been closed before calling close()

When trying to execute the below code, I am always getting the exception message as;

java.lang.IllegalStateException: This Realm instance has already been closed, making it unusable.

But if I comment out the database.close() call then it is working fine. What could be the reason for it?

Observable.defer(() -> Observable.create((ObservableOnSubscribe<String>) cacheEmitter -> {

                Realm database = Realm.getDefaultInstance();

                database.executeTransaction(realm -> {

                    RealmResults<ResponseCache> cache = realm.where(ResponseCache.class).findAll();
                    ResponseCache cacheData = new ResponseCache(null, "");
                    for(ResponseCache resCache : cache) {

                        if(resCache.getCategoryId().equals(searchType)) {
                            cacheData = new ResponseCache(resCache);
                            break;
                        }
                    }

                    String cacheResData = cacheData.getSearchResponse();
                    database.close();
                    cacheEmitter.onNext(cacheResData);
                });

            }))

Upvotes: 1

Views: 1324

Answers (1)

EpicPandaForce
EpicPandaForce

Reputation: 81539

Should be

try(Realm database = Realm.getDefaultInstance()) {
    database.executeTransaction(realm -> {
        RealmResults<ResponseCache> cache = realm.where(ResponseCache.class).findAll();
        ResponseCache cacheData = new ResponseCache(null, "");
        for(ResponseCache resCache : cache) {
            if(resCache.getCategoryId().equals(searchType)) {
                cacheData = new ResponseCache(resCache);
                break;
            }
        }

        String cacheResData = cacheData.getSearchResponse();
        cacheEmitter.onNext(cacheResData);
    });
}

Upvotes: 1

Related Questions