How to avoid race condition?

独自空忆成欢 提交于 2021-02-05 08:59:05

问题


I am make random 1:1 chat app with Flutter and Firestore. But I have race condition when I am connect second user to chat.

This my client app code for add second user to Firestore (first user is already add to Firestore document):

await chatRoomReference.setData({
  ‘secondUserUID': uid,
});

When second user tap to chat I am remove option to enter this chatroom from all client UI. But is possible that if third user tap to chat at same time (before UI get update from stream) he will also be add to database. Chat should not allow this. 


How to avoid the race condition?

Thanks!

UPDATE:

Each chat user is add as new document in separate user collection for chat.


回答1:


I think your button should check the number of people in the chat room then join the chat room.

checkBeforeJoinTheChatRoom()
    .then((numbOfPeople){
        if(numbOfPeople < 2){ 
            joinChat();
        }
    }
)

Edit: transaction may work in your case:

final DocumentReference postRef = Firestore.instance.document('posts/123');
Firestore.instance.runTransaction((Transaction tx) async {
  DocumentSnapshot postSnapshot = await tx.get(postRef);
  if (postSnapshot.exists) {
    await tx.update(postRef, <String, dynamic>{'likesCount': postSnapshot.data['likesCount'] + 1});
  }
});

Read more about : cloud_firestore_transactions



来源:https://stackoverflow.com/questions/54844403/how-to-avoid-race-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!