I'm using Firebase Firestore in my SwiftUI app project. At the start of the app, I want to read multiple documents from various collections.
Let's say I have collection A (1 document), B (2 documents) and C (4 documents). The data in the documents from A and B determine which documents from C I have to read.
Currently, I have a DatabaseHelper class which has a readCollection function for each collection (each of these readCollection functions call readDocument functions to create a listener for each required document). Each readCollection function as well as each readDocument function has a completion handler. At the start of the app, I start with reading collection A. After completing the read, it then starts reading B, and so on:
func listen(completion: @escaping () -> ()) {
readA() {
readB() {
readC() {
completion()
}
}
}
}
My app is waiting for the listen function to complete before displaying any data.
This approach is 'kind of working', HOWEVER, it does not seem to be the optimal approach. For example, if I read A, then I read both documents from B, the completion handler from B is called twice, which results in two calls for readC(), unless I count the document reads for B and only call the completion after the last read. THEN, the problem is, that only an update to the second document in B triggers the completion handler and reloads documents from C, but not an update to the first document in B.
Surely, there has to be a better logic to load my data from the database at the start of my app, which handles each document update during runtime correctly and without unneccessary double-reads.
Does anyone have a better approach? Thanks