List property becomes empty when multiple clients write to realm at the same time


#1

Hi everyone,

I’ve been having this problem for a while. I have my subclass of Object set up with a List property that stores another type of Object that I have defined. I’ll use this definition as an example.

class A: Object {
    @objc dynamic var id: String
    @objc dynamic var property1: String
    @objc dynamic var property2: String
    let items: List<B> = List<B>()

   @objc override class func primaryKey() -> String? {
       return "id"
   }
}

I have set up my realm to connect Realm Cloud so that I can listen for changes in the database on the client and update the UI accordingly. Now, whenever I write A to the realm using one client at a time, everything works fine: the A object on the other clients gets updated and the UI refreshes, reflecting the new changes.

However, when I perform write operations on the same A Object using two clients at the same time (or within a very very short amount of time), the List property becomes empty (items in the example above). When I check Realm Studio, I can see that the items property of A is an empty array. However, the actual items themselves have not been deleted. i.e. when I look up B in Realm Studio, the individual instances of B are there, but they are not in the List in A. In other words, the references to all the B objects have disappeared.

Why does this happen? Is it something about writing concurrently to the same object in the realm? I tried finding documentation on conflict resolution and what the behaviour for writing the same object from different clients is, but I couldn’t find anything.

I’ve been using add(:update:) to write to the realm. I saw that I can also use create(:value:update:). Should I be using this instead? Could that be the problem?

Would really appreciate any help on this. I’ve been stuck on this for ages and it’s been annoying me. I’ve been having to go into Realm Studio and manually restore all the references of B to A.

Many thanks,
Aero


#2

Can you try it out without subclassing the realm object?
Realm doesnt like subclassing :slight_smile:


#3

Sorry, I had the class definition wrong. Just updated it.


#4

What do you mean? You’re supposed to subclass Object


#5

Hmm, now it seems like good to me.
I have a few classes like this, but i am not tested with two clients at once (its not my priority).

Now i think i should… :smiley:

Do you have inverse relationships on the class B ?

Oh, one more: i think you should not use @objc on the primaryKey definition.


#6

Did you ever solve this ? Have you tried using LinkingObjects rather than List to maintain the relationships?