Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can my code know when Firebase has finished retrieving data?

I just want to ask about firebase retrieve data. How can i handle firebase retrieve data finished? I don't see any completion handler. I want to call some function after this firebase data retrieve finished. How can i handle???

DataService.ds.POST_REF.queryOrderedByChild("created_at").observeEventType(.ChildAdded, withBlock: { snapshot in
        if let postDict = snapshot.value as? Dictionary<String, AnyObject> {
            let postKey = snapshot.key
            let post = Post(postKey: postKey, dictionary: postDict)
            self.posts.append(post)
        }
    })
like image 457
Jack Avatar asked Jul 16 '16 05:07

Jack


1 Answers

In Firebase, there isn't really a concept of 'finished' (when listening to 'child added'). It is just a stream of data (imagine someone adds a new record before the initial data is 'finished'). You can use the 'value' event to get an entire object, but that won't give you new records as they're added like 'child added' does.

If, you really need to use child added and get notified when it's probably finished, you can set a timer. I don't know swift, but here's the logic.

  1. Set up your 'child added' event.
  2. Set a timer to call some finishedLoading() function in 500ms.
  3. Each time the 'child added' event is triggered, destroy the timer set in step two and create another one (that is, extend it another 500ms).

When new data stops coming in, the timer will stop being extended and finsihedLoading() will be called 500ms later.

500ms is just a made up number, use whatever suits.

like image 169
David Gilbertson Avatar answered Jan 25 '23 17:01

David Gilbertson