Realm Kotlin SDK ↔ AndroidX Lifecycle instance ownership and listener cleanup
0 reputation · 29 May 2024, 07:15 UTC
Designing ownership boundaries for Realm instances and change listeners when an Android screen is tied to AndroidX Lifecycle requires a clear interoperability contract between the Realm Kotlin SDK and Lifecycle components.
The SDK is thread-confined and historically requires explicit close. RealmChangeListeners and Kotlin Flows derived from Realm objects can hold strong references to observers. Lifecycle-aware helpers and internal reference counting exist, but close eligibility and automatic cleanup semantics differ between the legacy Java SDK and the newer Kotlin Multiplatform SDK and are version sensitive.
There is an unresolved decision about whether a Realm instance should be automatically closed when the owning Lifecycle reaches DESTROYED or whether explicit close calls remain required, and whether lifecycle-bound wrappers guarantee removal of listeners on configuration change.
What ownership model is considered canonical for per-screen versus shared Realm instances with AndroidX Lifecycle? Under which SDK releases does a lifecycle-bound wrapper guarantee listener removal on DESTROYED without explicit close? When is explicit close still required for thread-confined instances shared across components?