Search code examples
swiftfirebase-realtime-databaseconnection

How to both read and write when using onDisconnectUpdateChildValues - firebase swift


I am trying to decrement observerCount when a user disconnects. How do you do it?

My code:

let connectedRef = Database.database().reference(withPath: ".info/connected")
    
    connectedRef.observe(.value, with: { snapshot in
        
        guard let connected = snapshot.value as? Bool, connected else {
            completion(false)
            return
            
        }
        
        
        self.database.child("\(groupChatId)_A").onDisconnectUpdateChildValues(["observersCount": 0]){ (error, ref) in
            if let error = error {
                print("\(error)")
            }
            completion(true)
        }

        
    })

Solution

  • There is no way to read from the database in an onDisconnect handler. Essentially, the operation has to be a pure set, where the data you write is known when you attach the handler.

    Luckily for this use-case, Firebase added an atomic increment() operation a while ago, which is perfect here. I haven't used it in Swift myself, but it should be something like:

    .onDisconnectUpdateChildValues([
      "observersCount": firebase.database.ServerValue.increment(-1)
    ])