bigpotato
bigpotato

Reputation: 27507

Firebase: observing childAdded returns existing / old records?

I have a query (written in swift):

    FIRDatabase.database().reference(withPath: "\(ORDERS_PATH)/\(lId)")
      .child("orders")
      .observe(.childAdded, with: { firebaseSnapshot in

      let orderObject = firebaseSnapshot.value as! [String: AnyObject]

      let order = AppState.Order(
        title: orderObject["name"] as! String,
        subtitle: orderObject["item_variation_name"] as! String,
        createdAt: Date(timeIntervalSince1970: TimeInterval(orderObject["created_at"] as! Int / 1000)),
        name: "name",
        status: AppState.Order.Status.Pending
      )

      f(order)
    })

My database looks like this:

enter image description here

I want it to just listen all NEW incoming orders. However, every time it initially loads it fetched a bunch of existing orders with it, which isn't what I want.

I do have a created_at (an int that represents that time e.g. 1478637444000) on each of the orders, so if there's a solution that can utilize that that works too.

Is there something wrong with my query?

Upvotes: 3

Views: 3272

Answers (2)

Milligator
Milligator

Reputation: 159

Swift3 Solution:

Just write multiple observers.

You can retrieve your previous data through the following code:

queryRef?.observeSingleEvent(of: .value, with: { (snapshot) in


    //Your code

})

observeSingleEvent of type .value just calls once and retrieves all previous data

and then observe the new data through the following code.

queryRef?.queryLimited(toLast: 1).observe(.childAdded, with: { (snapshot) in

 //Your Code

        })

queryLimited(toLast: 1) with bserving of type .childAdded is being called every time that a new data is available

Upvotes: -2

Jay
Jay

Reputation: 35657

Observers always fire once and read in "all the data".

A .value observer reads in everything in the node at once, where as a .childAdded observer (from the docs)

This event is triggered once for each existing child and then again every time a new child is added to the specified path.

If you think about your question, what you are actually looking for is a sub-set of all of your data. This is achieved via a query.

Your query will be to observe all .childAdded events that occur after a certain timestamp. So that's what you need to do!

Craft an observe query leveraging queryStartingAtValue(the timestamp to start at) which will return all children added after that timestamp.

Upvotes: 9

Related Questions