I have a problem with understanding what is good practice on closing Realm instance, whenever I am running async transaction.
In my application I have many controllers and I do not pass into them Realm instance from activity, instead I create a new one each time it is needed and close it as soon as work is done.
However recently I found out that it is not working correctly, if I am closing realm instance when it is running async transaction.
Realm cacheRealm = RealmDelegate.getCacheRealm();
cacheRealm.executeTransaction(realm -> {
doSomeWork(response);
realm.copyToRealmOrUpdate(response);
}, callback);
cacheRealm.close();
This code above has one big problem, that callback is never launched, since I am closing realm instance before transaction is finished.
Therefore I am not sure how am I supposed to handle this situation. Am I supposed to pass instance of Realm object into each controller from activity or fragment, and handle closing of realm instances only over there? Or maybe there are other more elegant solutions to this problem?
Also another thing that I am wondering about is what happens, if I won't close the Realm db, and is there a way to check if all instances of Realm has been closed?
You can close the Realm in the callback instead? You have both an error and success callback to hook into: https://realm.io/docs/java/latest/#asynchronous-transactions
realm.executeTransactionAsync(new Realm.Transaction() {
@Override
public void execute(Realm bgRealm) {
User user = bgRealm.createObject(User.class);
user.setName("John");
user.setEmail("[email protected]");
}
}, new Realm.Transaction.OnSuccess() {
@Override
public void onSuccess() {
// Transaction was a success.
}
}, new Realm.Transaction.OnError() {
@Override
public void onError(Throwable error) {
// Transaction failed and was automatically canceled.
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With