尝试执行以下代码时,我总是收到异常消息;
java.lang.IllegalStateException:此Realm实例已被关闭,使其无法使用。
但是如果我注释掉database.close()调用那么它工作正常。可能是什么原因?
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);
});
}))
答案 0 :(得分:1)
应该是
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);
});
}