0

I am trying to poll my realtime database every 3 seconds with the iOS SDK to retrieve the latest 5 message objects.

I use the following code:

let query = rtdb.child("event/ID/chat")
                .queryOrdered(byChild: "createdAt")
                .queryStarting(atValue: <TIMESTAMP>)
                .queryLimited(toFirst: 5)

query.observeOnce(of: eventType) { snapshot in }

Let's say I have the following (simplified) data in my db:

{
    id: 1,
    createdAt: 123456781
},
{
    id: 2,
    createdAt: 123456782
},
{
    id: 3,
    createdAt: 123456783
},
{
    id: 4,
    createdAt: 123456784
},
{
    id: 5,
    createdAt: 123456785
},
{
    id: 6,
    createdAt: 123456786
},

I start my query with the timestamp 123456787. I then post another message with the timestamp 123456788. My query does not pick it up. Why?

If I instead start my query with the timestamp 123456782, it will return the messages with id 2, 3, 4, 5.

What am I doing wrong?

UPDATE

It's because of persistence being enabled. It just returns the locally cached data. That's stupid.

Tometoyou
  • 7,792
  • 12
  • 62
  • 108
  • Are you ordering them ascending or descending? – Tom Bailey Jun 08 '20 at 12:53
  • I see you are also using observeOnce, surely that means the updates for your second message with the higher timestamp won't be seen unless it already exists before you observe the query results? – Tom Bailey Jun 08 '20 at 12:58
  • @TomBailey I don't specify order so it's ascending. Re your second point, I am calling the observer again. It gets called every 3 seconds. – Tometoyou Jun 08 '20 at 13:08
  • Would it not be better to observe indefinitely? You should only receive updates if the underlying stream changes. As opposed to polling – Tom Bailey Jun 08 '20 at 13:15
  • @TomBailey I have an observer, but it's using way too much data transfer and costing tonnes. That's why I need to switch to polling. – Tometoyou Jun 08 '20 at 13:21
  • From your update it sounds like you're hitting this behavior: https://stackoverflow.com/questions/34486417/firebase-offline-capabilities-and-addlistenerforsinglevalueevent/34487195#34487195. As a rule: don't mix disk persistence and single value event listeners, as they simply don't work well together. – Frank van Puffelen Jun 08 '20 at 15:13

0 Answers0