Search code examples
iosswiftfirebaseobservers

Swift iOS Firebase- If something goes wrong when observing a node does withCancel: event trigger only once or everytime it loops through the children?


I have a ref with 3 children. I want to observe it using .childAdded or .value. There is a withCancel: event that runs if something goes wrong. Since I've been testing I've yet to have the withCancel: run so that is why I am asking this question.

If something does go wrong and the withCancel: runs will it run every time a loop happens or only once at the initial time of the query?

For eg. if the .childAdded or .value grabs the first child and it's successful, then when it goes to grab the second child there is a problem will the withCancel: run, but then it will try the third child which can either be a success or also canceled. This means I will definitely have the first child, I definitely won't have the second, but I may or may not have the third.

Or

Once the connection is made and the snapshot from the closure is run the withCancel: will never get a chance to fire and I'm guaranteed to get all 3 children? This means once the observer starts, if it gets to the first child I'm guaranteed to get the second and third because the withCancel: never fired once it started observing. Conversely before it even gets to the first child if withCancel: fires then there is no way I will get the second and third and I won't get anything at all.

            // or .value
ref?.observe( .childAdded, with: { [weak self](snapshot) in

         // do something with each snapshot

    }, withCancel: { [weak self](error) in

        // do something based on wether this will fire only once or can fire multiple times
        // for example if only once and I won't get anything then reload the tableView
        // if in can run multiple times then don't reload the tableView until it's finished. I have to add a limit to the query
})

Solution

  • The documentation states that the withCancel block fires when you no longer have permission to observe the reference. I'm not sure what you mean by "if something goes wrong", but that would not be the business of the withCancel block.