Search code examples
databaseduplicatesfirebase-realtime-databaseobservers

Duplicate data in array after user logins again Firebase observe method


Everything works fine until user logs out and logs back again. Seems like Firebase observe method is called twice. I tried to removeAllObservers in viewDidDisssaper and to removeObserver with handle but it did not help. I still get the duplicate data. What else I can try? Maybe my query is wrong? But then it would show the wrong results in the beginning..

Here is what I am using:

let ref = FIRDatabase.database().reference().child("Recent")

func observeRecent() {
        ref.queryOrdered(byChild: "sender_id").queryEqual(toValue: senderId()).observe(.value, with: { snapshot in

            Chats_VC.activeConversations.removeAll()
            for snap in snapshot.value as? [String: AnyObject] ?? [:] {
                let data = FIRDatabase.database().reference().child("Recent").child(snap.key)
                data.observeSingleEvent(of: .value, with: { snapshot in
                    let dict = snapshot.value as? [String: AnyObject] ?? [:]
                    let activeSnapshot = Recent()
                    //....
                    Chats_VC.activeConversations.append(activeSnapshot)
                    self.tableView.reloadData()
                })
            }
        })
      }

Solution

  • Could not find any relative answer. So I just check array for duplication and remove any duplicates