2

I have a messaging app with with models looking like this

public class Message {
    String message;
    List<String> reads;

    ... more logics
}

On firebase it looks like this

... [ 
   "myGeneratedMessageId" : {
       "from":"userId1",
       "reads":[
          "userId2",
          "userId3"
       ]
   }, ...

]

When a user sees it the user's id should be added to the array. Will I have to worry about overwriting values in that array if multiple users are seeing it simultaneously? And what do I do to make that not happening?

For clarification,

User 1 sees the message -> sends the user id to that array (I guess by adding it to the local array and then updating that child on the message on Firebase)

User 2 sees the message before User 1 updates it, updating it too - with adding only his id to the array and updating the child on Firebase

Edit: Updated usage (potential problem still exists)

I made reads into a hashmap with id : boolean

 ... 
 "message": "Hello world!",
 "from": "userId1",
 "reads":[
     "userId2": true,
     "userId3": true
 ], ...

Inside model markAsRead()

if(reads == null) {
   reads = new HashMap<String, Boolean>(); <-- could cause problem
} 

if(reads.get(userId) == null) {
   reads.put(userId, true);
}

.. save logics

A user could still create the hashmap if there is none, making the other users' new hashmap rewrite it.

Jonas Borggren
  • 2,591
  • 1
  • 22
  • 40
  • The potential for multi-user conflicts is large when using arrays. This is one of the many reasons why [Firebase recommends against using arrays](https://firebase.googleblog.com/2014/04/best-practices-arrays-in-firebase.html) and [proposes a different way to handling list structures](https://firebase.google.com/docs/database/android/lists-of-data#read_and_write_lists). But what you have looks like it might be [better served with a set](http://stackoverflow.com/questions/40656589/firebase-query-if-child-of-child-contains-a-value), which very conveniently solves the problem you outline. – Frank van Puffelen Feb 16 '17 at 20:19
  • I think the problem will be avoided if you made changes (when user read) directly into database, without adding it into your local `HashMap` first. I mean by using `...getReference("myGeneratedMessageId/reads/" + user.getUid).setValue(true)`. And since the message object is continuously synced, the value of read `HashMap` will also be updated – koceeng Feb 17 '17 at 03:58

1 Answers1

2

If I understand it correctly, you are worried about concurrent updates on your firebase database.

If that so, you can check the section

Save data as transactions

And check this answer:

Firebase - Multiple users simultaneously updating same object using its old value

Community
  • 1
  • 1
caiolopes
  • 561
  • 8
  • 14