Firebase - Two offline devices modifying same data and order of changes
Asked Answered
T

2

6

I have an Android app, that keeps track of some items and their quantities.

What I need is a way for the user to modify data on multiple devices while being offline, with proper synchronization order.

I don't know how to best explain it, so I'll give an example:

  1. Device A changes quantity of item to 5.
  2. Device B changes it to 3.
  3. Device B goes online, changes data on server, like it should, to 3.
  4. Device A goes online and replaces that data with 5 which is an older change and shouldn't be done.

Can this situation be prevented natively in Firebase, or should I, for example, use timestamps on items myself, and replace it only if newer?

Thanks.

Thibault answered 4/12, 2016 at 16:21 Comment(0)
T
5

Adding timestamp field to every item in database and writing security rule in firebase seems to work.
The thing to consider is, when offline, the only timestamp I can get is from the device, not from the server, so it can sometimes lead to overwrite of data that we don't want. Still it works good enough for this project.
Below is the database rule needed to check those timestamps:

"$name" : {
         ".write": "!data.exists() || (newData.child('timestamp').isNumber() && data.child('timestamp').val() <= newData.child('timestamp').val())"
      }

It says: "you can write if there's no data, or stored data has older timestamp that new request"
Important thing to remember while making those is, that parent nodes overwrite rules in children. That means any authentication of write should be done on this level too.

Thibault answered 8/12, 2016 at 11:46 Comment(0)
C
3

You can use device timestamp to persist the latest data, and reject any data modification performed prior... eg: if your data is structured as follows

{
    'users': {
        'userId': {
            'timestamp': 1496341800000,
            'var1': 'abc',
            'var2': 'abc'
        }
    }
}

on every update to object for any value, also update timestamp, and add the following rule in firebase console

{
"rules": {
    ".read": "auth != null",
    ".write": "auth != null",
    "users": {
        "$uid": {
            ".write": "$uid === auth.uid",
            ".validate": "!data.exists() || data.child('timestamp').val() <= newData.child('timestamp').val()"
        }
    }
}
}

whenever multiple devices comes online and update the firebase database, data having the latest timestamp will be updated.

Criseldacrisey answered 3/6, 2017 at 5:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.