Realm in FragmentStatePagerAdapter

I have some trouble opening and closing realm instances correctly in a FragmentStatePagerAdapter (Android / Kotlin). I usually open an async instance in my Fragments in the onStart() Method and close it in onStop() and onDestroyView() as you have suggested in the docs.

In case of the PagerAdapter this leads to multiple open instances of the same kind simultaneously as I have a fragment for the pager adapter and multiple fragments for each tab. Each needs access to the same realm. When switching between the tabs the app might crash due to an Invalid Object Error - The realm instance has already been closed. Does this happen because wrong instances are getting closed when multiple instances are open? For now, I resolved the issue by opening the instance only once in the Adapter-Fragment and saving it to a global variable and accessing the global variable in each ‘Tab’-Fragment. However, I’m not sure, whether it is a good idea to have a realm instance in a global variable or if that might lead to other problems.

Another issue is: In the tab fragments users can insert data through a dialog. The data is then written into realm asynchronously using: globalRealmInstance.executeTransactionAsync{}. However, if the app is minimized and opened again, the realm can’t be longer accessed as it has been closed in the onStop method. The newly started async realm instance seems not be accessible in my dialog which needs to run on the main thread. Hence, to insert the data I need to open a new instance, before using the async transaction. To cover both cases (app has been minimized or not) I open a new instance, without checking if the globalRealmInstance is valid. My question now is, if it is wise to open a new instance even if the other instance might still be valid and opened or if I should check if the realm is valid and only using a new instance if the instance has been closed.

1 Like