Realm instance for observable query is closed by another query

I have problems with realm my realm instances. I only use realm default instance. For each query/update operation, I get a realm instance with Realm.getDefaultInstance(), and I close it when I finish the operation.

My problem is that one of those queries is an observable query. I only close this realm instance when the subscription is finished. Meanwhile, other operations can close its realm instance. I know that realm instances are obtained from a cache, so I think that one of this operations are closing the same realm instance that I get when I create my observable query, because after some operations, my observable query stops emmiting items, and when I finish my subscription, I get an exception saying that my realm instance is already closed. Does it have sense? How can avoid that?

I think this is what is happening:

1. Start observable query -> Realm observable instance opened
2. Start database update 1 -> Realm query1 instance opened
3. Finish database update 1 -> Realm query1 instance closed

...

4. Start database update X -> Realm observable instace opened again <- PROBLEM
5. Finish database update X -> Realm observable instance closed
6. Finish observable query -> Realm observable instance closed again -> EXCEPTION

This is the code where I perform my observable query:

Realm realm = Realm.getDefaultInstance();

return realm.where(Message.class)
        .findAll().asObservable()
        .filter(RealmResults::isLoaded)
        .map(realm::copyFromRealm)
        .doOnUnsubscribe(() -> realm.close());

Is there any way to get a brand new realm instance which is not cached so that nobody can get the reference and close it?

Upvotes: 0

Views: 274

Answers (1)

EpicPandaForce
EpicPandaForce

Reputation: 81568

Actually, Realm's Rx integration uses the RealmResults's RealmConfiguration to increase the Realm ref-count internally (inside the Observable), so you don't need to do such magic. You could do:

try(Realm realm = realm.getDefaultInstance()) {
    return realm.where(Message.class)
        .findAll()
        .asObservable() // synchronous query is always loaded
        .map(realm::copyFromRealm)
}

And it'd work. Although I don't know for sure if it helps solves your problem.

Upvotes: 1

Related Questions