[Question] Working with several synced realm devices


#1

First I would like to apologize if I am asking this question in wrong section of Forum. I am not sure to post it in Realm Swift or Realm Cloud section. As this question is regarding Realm Cloud, hence I decided to ask in this section.

I am still testing Realm Cloud to see whether it may work well with my current whole system. I am using Realm Swift for it

Let’s say I have realm cloud with object

TotalStock

  • total: Int = 10

And here is the scenario:
Device A and B synced with the Realm Cloud at first, hence those 2 devices come with TotalStock with property total = 10

Device B disconnected from Internet.
Device A made a changes to total , -2 hence total at Realm cloud already 8
Device B while still disconnected from Internet made changes to total, -1 . Temporary total is 9

When Device B is connected to internet, it synced up automatically to the Realm Cloud Server and overlapped the 8 to 9. Which in this behavior, it is expected to reflect amount 7.

Here is the basic code that I use to do manipulation

try! realm.write {
        self.items[0].total -= 1
}

How can I anticipate this scenario with Realm Cloud.

Any help given is highly appreciated. Thanks


#2

Hello,
and welcome to the multiple device sync hell :slight_smile:
In our case, we went the way where you use another table for the transactions - the current value is calculated with that. Those transactions have a createdAt timestamp, the exact date of the transaction.

With this, we know the exact values and eliminate the double buys (when the user buys something with the offline device, then on the online device but don’t have enough money)

If somebody has a better idea please tell me.


#3

Alvin,

Freeubi has the right idea. Currently the best way to keep a running counter in RealmSwift is to create a List of objects that tracks the increments, then use the sum of those values.

We have an example application in Swift demonstrating this process in detail.


#6

Hi eric.mossman,

Thanks for your reply. Really appreciate that.

Inside the sample application documentation there is Method 2: Counter. Is there any explanation about this in present time?

Thank you so much!