How about adding a noOfMessages
node under each group, and updating it every time with the group messages count changes. You will have to make a query to count the noOfChildren some time, right? But this way not every time.
For me i just created a func countNodes()
which would be fired every time a child is added or you can use a timeInterval in NSTimer, which as you say is expensive.
But with .childAdded you will only receive appended key-value pair not the entire of the node's value, and then all you gotta do is update your noOfMessages
node's value with the no of .childAdded count.
As for in your case, change your structure to:-
chats :{
group1 : {
...
},
},
noOfMessages :{
group1 : 18,
group2 : 76,
....
}
Add an observer to your each group of eventType .childAdded
.
FIRDatabase.database().reference().child("chats/group1").observeSingleEvent(of: .childAdded, with: {(snap) in
//Run transaction to update your noOfMessage Count
})
To get the noOfMessages count:-
FIRDatabase.database().reference().child("noOfMessages/group1").observeSingleEvent(of: .value, with: {(snap) in
let count = snap.value as! Int
})