How to pipeline several request to Firebase in order to fetch data from multiple nodes at the same time
Probably the best way to do this in Swift would be to use DispatchGroups -
var nodes: [String] = ["node1", "node2", "node3", "node4"]
let dispatchGroup = DispatchGroup()
for node in nodes {
dispatchGroup.enter()
Database.database().reference().child(node).child(uid).observeSingleEvent(of: .value, with: { (snapshot) in
//Do something
dispatchGroup.leave()
}
}
dispatchGroup.notify(queue: .main, execute: {
//Called when all requests have been fulfilled
})
Google Firestore - How to get several documents by multiple ids in one round-trip?
if you're within Node:
https://github.com/googleapis/nodejs-firestore/blob/master/dev/src/index.ts#L978
/**
* Retrieves multiple documents from Firestore.
*
* @param {...DocumentReference} documents - The document references
* to receive.
* @returns {Promise<Array.<DocumentSnapshot>>} A Promise that
* contains an array with the resulting document snapshots.
*
* @example
* let documentRef1 = firestore.doc('col/doc1');
* let documentRef2 = firestore.doc('col/doc2');
*
* firestore.getAll(documentRef1, documentRef2).then(docs => {
* console.log(`First document: ${JSON.stringify(docs[0])}`);
* console.log(`Second document: ${JSON.stringify(docs[1])}`);
* });
*/
This is specifically for the server SDK
UPDATE: Cloud Firestore Now Supports IN Queries!
myCollection.where(firestore.FieldPath.documentId(), 'in', ["123","456","789"])
Firebase performance - fetching nodes
Doing a "client-side join" in Firebase is not nearly as expensive as you might expect. See this answer: Speed up fetching posts for my social network app by using query instead of observing a single event repeatedly
If you directly access the node (only calling new Firebase()
and child()
), no query is needed, so you won't need an index. If you're calling orderByChild()
or orderByValue()
you should add an index.
Firebase real time database, get values from different locations in one snapshot
You can only load:
- a single complete node
- a subset of all child nodes matching a certain condition under a single node
It seems that what you are trying to do is get a subset of the child nodes from multiple roots, which isn't possible. It actually looks like you're trying to do a join, which on Firebase is something you have to do with client-side code.
Note that loading the subsequent nodes is often a lot more efficient than developers expect, since Firebase can usually pipeline the requests (everything goes over a single web socket connection). For more on this, see http://stackoverflow.com/questions/35931526/speed-up-fetching-posts-for-my-social-network-app-by-using-query-instead-of-obse/35932786#35932786.
Get data from multiple references from Firebase realtime database in one query javascript
To load multiple nodes based on their key, you'll need a separate call for each node/key. It's essentially a client-side join of the data from the two nodes:
const usersMessages = firebase.database().ref(`users/${userUid}/messages`);
usersMessages.on('value', async (snapshot) => {
let usersMessages = [];
snapshot.forEach((child) => }
let messageId = child.key;
let messageSnapshot = await firebase.database().ref(`messages/${messageId}`).get()
const message = messageSnapshot.val();
usersMessages.push(message);
});
});
Firebase : How to removeObserver(withHandle:) after observeSingleEvent()?
Since databaseReference.observeSingleEvent(...)
doesn't return a handle that you can remove the only option is to use databaseReference.observe(...)
.
Just remove the handle manually once you need to OR when the first event fires.
Update
Try using this extension:
public extension FIRDatabaseReference {
@discardableResult
public func observeOneEvent(of eventType: FIRDataEventType, with block: @escaping (FIRDataSnapshot) -> Swift.Void) -> FIRDatabaseHandle {
var handle: FIRDatabaseHandle!
handle = observe(eventType) { (snapshot: FIRDataSnapshot) in
self.removeObserver(withHandle: handle)
block(snapshot)
}
return handle
}
}
Related Topics
Can't Upload .Ipa from Xcode 8, "The Info.Plist Indicates a iOS App, But Submitting a Pkg or Mpkg."
Missing Required Module Firebase - Jenkins Build Error
Loading Image from Assets to Nsimage Keep Getting Error, Expecting Nsimage.Name
Cocoapods Framework with Dependencies - Include of Non-Modular Header Inside Framework Module
Swift: How to Add a Class Method in 'string" Extension
More Precision Than Double in Swift
Uimarkuptextprintformatter and MAC Catalyst
Location Access Request in iOS 11
Is There a Method to Check The UIcollectionview Item Drag Cancellation If The Item Wasn't Moved
Table View's 'Cellforrow(At:)' Is 'Nil' in Unit Test
Convert Time String into Date Swift
Xcode Failed to Resolve Dependency Firebase - Googleappmeasurement Does Not Match Requirement
"'Init' Is Deprecated" Warning After Swift4 Convert
Swift: How to Add a Class Method in 'string" Extension
Variable with Getter/Setter Cannot Have Initial Value, on Overridden Stored Property
Nstoolbarflexiblespaceitem Is Constraint to Nssplitviewitem in Swift
Using an Avplayer Returns a "Non-Multipath Connection" Error