问题
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