Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle timeout in queries with Firebase

Tags:

firebase

I noticed that if I execute a query in Firebase and the database server is not reachable, the callback waits just forever (or until the server is reachable again).

Where this behavior is quite natural for the asynchronous approach used, it would nevertheless be useful to have an easy way to specify a timeout so you could inform the user about the status.

Is there such an option and I just missed it - or it really missing? Or how would you solve this problem?

like image 843
magicwerk Avatar asked Apr 27 '16 16:04

magicwerk


People also ask

How much traffic can Firebase handle?

The limit you're referring to is the limit for the number of concurrently connected users to Firebase Realtime Database on the free Spark plan. Once you upgrade to a payment plan, your project will allow 200,000 simultaneously connected users.

How do I use Firebase REST API?

You can use any Firebase Realtime Database URL as a REST endpoint. All you need to do is append . json to the end of the URL and send a request from your favorite HTTPS client. HTTPS is required.


2 Answers

Here's my solution for the Firebase iOS SDK, this may be helpful for others:

extension DatabaseReference {

    func observe(_ eventType: DataEventType, timeout: TimeInterval, with block: @escaping (DataSnapshot?) -> Void) -> UInt {

        var handle: UInt!

        let timer = Timer.scheduledTimer(withTimeInterval: timeout, repeats: false) { (_) in
            self.removeObserver(withHandle: handle)
            block(nil)
        }

        handle = observe(eventType) { (snapshot) in
            timer.invalidate()
            block(snapshot)
        }

        return handle
    }

}

Usage:

database.child("users").observe(.value, timeout: 30) { (snapshot) in

    guard let snapshot = snapshot else {
        // Timeout!
        return
    }

    // We got data within the timeout, so do something with snapshot.value
}
like image 119
Jonathan Ellis Avatar answered Sep 21 '22 16:09

Jonathan Ellis


you can manage yourself a timer controller that after x seconds remove the listener to you firebase reference. It's very simple, just one line of code in android for example.

You can see the code for the web (Detaching Callbacks section): https://www.firebase.com/docs/web/guide/retrieving-data.html

or for android (Detaching Callbacks section): https://www.firebase.com/docs/android/guide/retrieving-data.html#section-detaching

same section for IOS ;)

like image 40
Federico Ponti Avatar answered Sep 20 '22 16:09

Federico Ponti