0

I am trying to retrieve the timestamp of the last child in chatRef. It works fine when persistence is disabled. When it is enabled it returns an object in between instead of the last one.

How is this possible?

       self.chatRef.queryOrderedByChild("timestamp").queryLimitedToLast(1).observeSingleEventOfType(.Value, withBlock: { (snapshot) -> Void in
            for child in snapshot.children {

                let childSnapshot = snapshot.childSnapshotForPath(child.key!!)

                if let object = childSnapshot.value as? [String: AnyObject] {
                    var timestamp = (object["timestamp"] as? NSNumber)!.longLongValue 
                    timestampQueryValue = NSNumber(longLong: timestamp)
                    print("timestamp of childSnapshot: \(timestampQueryValue)") 
                    // actually prints the timestamp of an older object when persistence is enabled
                }
            }
        })
    }
MJQZ1347
  • 2,607
  • 7
  • 27
  • 49
  • 1
    That is expected behavior on an API level (even though it's seldom what you want functionally). The firebase client eagerly fires with the value as it knows it, which will come from cache. Interestingly enough, the next `observeSingleEventOfType` will then return the updated value. In short: don't use `observeSingleEventOfType` when you care about the value being current. I'll find a answer where that is better explained. – Frank van Puffelen Jun 10 '16 at 23:20
  • Thanks for your explanation. What would you suggest instead of using `observeSingleEventOfType`? – MJQZ1347 Jun 10 '16 at 23:21
  • Observing a regular `.Value` event. When you combine that with disk persistence, you'll (potentially) get two `.Value` events: one for the local/cached version and then one with the value from the server (if it was different). – Frank van Puffelen Jun 10 '16 at 23:25
  • Unfortunately it doesnt work always. `self.chatRef.queryOrderedByChild("timestamp").queryLimitedToLast(2).observeEventType(.Value` doesn't always return the last two objects. I also tried it with `queryLimitedToLast(4)`. Sometimes it works, sometimes it doesn't. This is kind of odd. – MJQZ1347 Jun 10 '16 at 23:44
  • That might be caused by using a `.Value` event, which will only fire if the "complete" data is available. See this answer for a good explanation of that behavior: http://stackoverflow.com/questions/37276499/what-actually-happens-when-persistence-is-enabled-in-firebase/37280451#37280451 – Frank van Puffelen Jun 11 '16 at 01:04
  • @FrankvanPuffelen there should be a way to only retrieve the latest data from the server skipping the local cache. I often need this in my app and it is somewhat annoying to react to old data. BTW: What's the use of `observeSingleEventOfType` when it only gives back the local data? – MJQZ1347 Jun 25 '16 at 17:43

0 Answers0