Firestore snapshot - are dynamic queries possible? - firebase

I have two listeners - one for the user's profile and one for the rooms the user is in; the uids of the rooms are stored in an array on the profile, i.e. the query for the second listener depends on data from the first.
It looks like this (simplified):
// profile listener
onSnapshot(profileRef, (snapshot) => setProfile(snapshot.doc.data())
// rooms listener
const roomsQuery = query(
collection(db, "rooms")
where("uid", "in", profile.roomsList)
)
onSnapshot(roomsQuery, (snapshot) => setRooms(snapshot.docs)
When the user is added to a new room, the profile updates with the new roomsList. But the rooms snapshot doesn't update - presumably because the query can't be updated dynamically.
Question
So, is there a way of updating the listener's query (i.e. keeping the same listener), or do I have to unsubscribe from the existing listener and re-subscribe with the new query every time profile is updated?
Versions
Using the new V9 of the Javascript sdk

Firestore queries are immutable, so there's no way to change the condition once the query has been created. You'll indeed have to attach a listener to a new query to get the updates roomsList. If you enable offline persistence though, the overlapping documents between the queries will be read from the local cache.
Also see: How to constantly update query for Firebase Realtime Database with LiveData and ViewModel in Android

Related

Nested snapshot listeners

I use Google Firestore for my iOS app built in Swift/SwiftUI and would like to implement the Snapshot listeners feature to my app.
I want to list all documents in debts collection in realtime by using snapshot listeners. Every document in this collection has subcollection debtors, which I want to get in realtime for each debts document as well. Each document in debtors has field userId, which refers to DocumentID in users collection which I would also love to have realtime connection on (for example when user changes his name I would love to see it instantly in the debt entity inside the list). This means I must initialize 2 more snapshot listeners for each document in debts collection. I'm concerned that this is too many opened connections once I have like 100 debts in the list. I can't come up with no idea apart from doing just one time fetches.
Have anyone of you ever dealt with this kind of nested snapshot listeners? Do I have a reason to worry?
This is my Firestore db
Debts
document
- description
- ...
- debtors (subcollection)
- userId
- amount
- ...
Users
document
- name
- profileImage
- email
I uploaded this gist where you can see how I operate with Firestore right now.
https://gist.github.com/michalpuchmertl/6a205a66643c664c46681dc237e0fb5d
If you want to read all debtors documents anywhere in the database with a given value for userId, you can use a collection group query to do so.
In Swift that'd look like:
db.collectionGroup("debtors").whereField("userId", isEqualTo: "uidOfTheUser").getDocuments { (snapshot, error) in
// ...
}
This will read from any collection name debtors. You'll have to add the index for this yourself, and set up the proper security rules. Both of those are documented in the link I included above.

How to properly update a Firestore query snapshot of an active stream?

I have a flutter app that searches for people on Firestore database based on different criteria such as city, country, region, etc. The app has the criteria as user-input that can be chosen then applied with a click of a button. When the button is clicked, the function below is called:
CollectionReference collectionReference = Firestore.instance.collection("profiles");
void getResults() {
// getQuery is a function that adds 'where' statements
// (e.g., .where("city", isEqualTo: "Paris);
Query query = getQuery(collectionReference, filters);
Stream<QuerySnapshot> snapshots = query.snapshots();
snapshots.map((docs) => docs.documents).listen((onData){
myStreamController.add(onData);
}
}
With the code above, a new query is created even if the existing stream contains all the data that is needed. For example, the user first retrieve all people from France first, then retrieves all the people from Paris only by updating the filter.
Since the existing stream already have all people from Paris, is it possible to dynamically update the query without creating a new stream/query?
What I'm trying to achieve here is that I want Firestore to take advantage the cache instead of retrieving all the documents again.
Firestore doesn't support dynamically changing the parameters of an active query. If you want to change the filters or ordering of an active query, you will have to stop the first query, create a new Query object, then execute the new query.

Firestore, fetch only those documents from a collection which are not present in client cache

I am implementing a one-to-one chat app using firestore in which there is a collection named chat such that each document of a collection is a different thread.
When the user opens the app, the screen should display all threads/conversations of that user including those which have new messages (just like in whatsapp). Obviously one method is to fetch all documents from the chat collection which are associated with this user.
However it seems a very costly operation, as the user might have only few updated threads (threads with new messages), but I have to fetch all the threads.
Is there an optimized and less costly method of doing the same where only those threads are fetched which have new messages or more precisely threads which are not present in the user's device cache (either newly created or modified threads).
Each document in the chat collection have these fields:
senderID: (id of the user who have initiated the thread/conversation)
receiverID: (id of the other user in the conversation)
messages: [],
lastMsgTime: (timestamp of last message in this thread)
Currently to load all threads of a certain user, I am applying the following query:
const userID = firebase.auth().currentUser.uid
firebase.firestore().collection('chat').where('senderId', '==', userID)
firebase.firestore().collection('chat').where('receiverId', '==', userID)
and finally I am merging the docs returned by these two queries in an array to render in a flatlist.
In order to know whether a specific thread/document has been updated, the server will have to read that document, which is the charged operation that you're trying to avoid.
The only common way around this is to have the client track when it was last online, and then do a query for documents that were modified since that time. But if you want to show both existing and new documents, this would have to be a separate query, which means that it'd end up in a separate area of the cache. So in that case you'll have to set up your own offline storage on top of Firestore's, which is more work than I'm typically willing to do.

Can the Date in a firestore query (onsnapshot) be kept current

In my web app I fire off a query to gather all recent messages for a user and then use an onsnapshot to show these messages in a feed. In my app some messages get posted to the future so I only want messages from now or earlier in the feed.
var query = firebase.firestore()
.collection('messages')
.where('owner','==',userID)
.where('timestamp','<',new Date())
.orderBy('timestamp', 'desc')
.limit(25);
The user can then create new messages and I want those added to the feed displayed in the app. After adding a new message do I have to cancel the onSnapshot listener and execute a new query with an updated current Date? Or is there a way for this query to update the time lookup so that the onSnapshot is always getting newly posted messages?
If you want to change any of the query parameters, you need to build a new Query object with the new values and add a snapshot listener to it..

How to avoid redundantly downloading data when using switchMap and inner observables in RxFire?

I have some RxFire code that listens to a Firestore collection query (representing channels) and, for each of the results, listens to a Realtime Database ref for documents (representing messages in that channel).
The problem I'm running into is that the Realtime Database documents are re-downloaded every time the Firestore query changes, even if they're for a path/reference that hasn't changed.
Here's some pseudo-code:
collection(channelsQuery).pipe(
// Emits full array of channels whenever the query changes
switchMap(channels => {
return combineLatest(
channels.map(channel =>
// Emits the full set of messages for a given channel
list(getMessagesRef(channel)),
),
);
})
)
Imagine the following scenario:
Query intially emits 3 Firestore channel documents
Observables are created for corresponding Realtime Database refs for those 3 channels, which emit their message documents
A new Firestore document is added that matches the original query, which now emits 4 channel documents
The previous observables for Realtime Database are destroyed, and new ones are created for the now 4 channels, re-downloading and emitting all the data it already had for the previous 3.
Obviously this is not ideal as it causes a lot of redundant reads on the Realtime Database. What's the best practice in this case? Keep in mind that when a channel is removed, I would like to destroy the corresponding observable, which switchMap already does.

Resources