简体   繁体   中英

Realm in FirebaseMessagingService

I am using realm in my firebase service and i am closing the instance of realm in my finally block but the problem arises when i perform an asynchronous operation in my try block in which case the finally executes before the async complete and the realm instance is closed which causes the app to crash since the async operation performs realm related tasks.

try {
 // perform async task that requires realm
} catch (Exception e) {
    e.printStackTrace();
} finally {
    if (realm != null && !realm.isClosed())
        realm.close();
}

This is what the code roughly looks like.If i try closing the realm instance anywhere else i get an error saying that i am accessing the realm instance from the incorrect thread,is there a way i can wait until the async operation is completed and only then close the realm instance.

So, you really can't perform an asynchronous task inside a try/catch block.

... and by "can't" I don't mean that it is bad practice, I mean that it is simply not possible, by the very definition of "asynchronous".

What you are doing inside the try/catch block is enqueuing the task, for later execution. Once the task is enqueued ( not executed! ) the try/catch block is exited.

If you want the try/catch block around the asynchronously executed code, you need to execute it at part of the asynchronous task.

Furthermore, as you will see in the documentation , you cannot pass most Realm objects between threads. You cannot open the realm on some thread and then pass it, open, to an asynchronous task.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM