Inconsistent object load for recently saved objects


(Maxime Britto) #1

Hello,

I’m having issue when reloading recently modified object from the Realm.
My objects have many relationships, and as soon as I’ve loaded them from realm I’m converting them to a non realm version of the same class :

val loadedPoint = realm.where(realmClass).equalTo("id", id).findFirst()
if (loadedPoint != null) {
    val finalObject = loadedPoint.toModel()
}

For all my classes I have a model class that knows nothing about realm (example : Practice) and a realm model class to do the saving/loading (example : RPractice).
The toModel() function simply creates a Practice object from the RPractice object data that Realm loaded for me.
The RPractice class contains a list of RPlot objects, which contains a list of RSamplingPoint objects.
The toModel() recursively converts every objects from the list by calling toModel() on them.

My issue is that frequently, some of the RSamplingPoint do not have the latest version of the data I saved into the Realm. I’m sure to have the data that was saved before this last session of my app, but all the data modified since I launched the app is unreliable : sometimes I get the new version, sometimes I get the old version.

I always use the same Realm object, I do not use the platform on this project, and I save using this code :

realm.beginTransaction()
realm.copyToRealmOrUpdate(savedObject)
realm.commitTransaction()

Do you have any idea why I have this issue ?

Thanks for your help :slight_smile:


(Maxime Britto) #2

I kept investigating and I found some interesting clues by logging my thread ids and realm object references.
I use Kotlin coroutines to load realm data in background threads and by default, coroutines have a pool of Threads already created they can use.
The Realm.getDefaultInstance() actually creates and returns an instance of Realm by thread. If later, we ask it again on a different thread, we get a new instance, but if we call it again from the same thread we get the same reference.
Those instances may have an integrated cache because depending on which one I ask the data, I get old or new data.
The instances that were created before I updated the data do not know the new data that was updated by a new instance (other thread).

I worked around the issue by disabling the pool and creating a new thread every time but it’s bad for performance.

Aren’t Realms supposed to be able to sync between threads as long as we keep separate object per threads ?