Reputation: 111
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:
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.
Upvotes: 6
Views: 1325
Reputation: 2456
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.
Upvotes: 3
Reputation: 111
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.
Upvotes: 5