Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Realm - how to close realm instance with async transaction

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?

like image 523
Kandyzowana Papaja Avatar asked Feb 15 '16 04:02

Kandyzowana Papaja


1 Answers

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.
        }
    });
like image 80
Christian Melchior Avatar answered Nov 14 '22 06:11

Christian Melchior