Realm IllegalStateException: accessing managed objects across threads during sync writes
0 reputation · 07 Jun 2020, 17:11 UTC
Goal
I want to pass a managed Realm object from the main thread to a background worker so a heavy write transaction does not block the UI, while keeping the object usable for reading its current field values.
Constraint and uncertainty
My understanding is that Realm managed objects are thread-confined: an instance obtained on one thread cannot be used on another, and doing so raises an IllegalStateException. The documented pattern seems to be re-querying by primary key on the destination thread, or copying values into an unmanaged object first. What I am unsure about is the exact boundary: does the confinement apply to the object instance only, or also to live collections and any Realm instance opened on the main thread? I also want to know whether frozen objects change this behavior in current Kotlin SDK versions (assume a recent 1.x release).
Questions
- Is passing only the primary key and re-querying on the background thread the required pattern, or is there a supported way to share a managed reference?
- Do frozen objects and frozen results bypass thread confinement entirely, and are they safe to hand to a coroutine worker?
- Does the same restriction apply to an open
Realminstance itself, requiring a separateRealm.open()call per thread?