How to match users randomly with Firebase

2.1k Views Asked by At

I'm trying to create a game where users are matched with each other randomly using Firebase.

My idea to match them is like this:

  1. User A comes, reads list of games. If there aren't any games waiting start game. Sets himself as initiator, opponent as null.
  2. User B comes, reads list of games. Finds User A's game (opponent is null) and joins it (he becomes the opponent)
  3. What happens if User C comes between the moment where User B read the games list and the moment User B wrote himself as the opponent (for him opponent would still be null). Basically the concurrency problem.

I've read about transactions but I'm not 100% sure they help in this case (Read games with no Opponent, Write opponent to one of the games) because I've seen them used a lot in increasing values rather than reading/writing data.

1

There are 1 best solutions below

0
On

Transactions blocks are used for concurrency. What they do is prevent issues when two users attempt to write to the same area at the same time. Like you said this is commonly seen with likes. So if the game currently only has 1 player and you save a value of 0 so other players know the game is "open". When a player attempts to connect to that game they write to that area and change the 0 to a 1. If another player attempted to connect at the same time their transaction block will now fire. When they get the data they will see a 1 though not a zero. At this point you back out and look for a new game. Not sure if this is the best method, but it should work.