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?


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("john@corporation.com");
        }
    }, 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.
        }
    });
链接地址: http://www.djcxy.com/p/90262.html

上一篇: Bootstrapping混合角1 + 2应用程序

下一篇: 如何使用异步事务关闭领域实例