Reputation: 1175
I have two apps that access the same firestore database. The 'User' app listens for changes to a document in a collection that doesn't exist until the 'Admin' app creates it. Here is the code:
Stream<DocumentSnapshot>logStream = FirebaseFirestore.instance
.collection('companies')
.doc(companyId)
.collection('log')
.doc(DateFormat('yyyy-MM-dd').format(DateTime.now()))
.snapshots();
}
The problem is that I cannot start listening to 'logStream' unless it exists.
Is there a way to check when it's created and then start listening?
Upvotes: 1
Views: 2066
Reputation: 5829
You can't start listening to stream immediatly after the document is created, that is not something that Firestore supports natively. So in order to do this you are going to have make a create a function that is called sporadically to check this until it is created, this function will make a get()
, check if the document exists and if positive start listening to it.
You can use StreamCompleter
, as mentioned in the comments, to listen to an "empty" stream before that without triggering any actions, but the calls to check existence of the document mentioned earlier will still need to be made, so you code can look like this:
var db = FirebaseFirestore.instance;
var completer = StreamCompleter<DocumentSnapshot>();
Stream<DocumentSnapshot>logStream = completer.stream();
// this function will need to be called sporadically
checkDocumentExists(completer);
checkDocumentExists(completer){
var reference = db.collection('companies')
.doc(companyId)
.collection('log')
.doc(DateFormat('yyyy-MM-dd').format(DateTime.now()));
reference.get() => then(function(document) {
if(document.exists){
completer.setSourceStream(reference.snapshots());
}
}
}
If you can't progress with your app execution until the document exists you can create an keep calling checkDocumentExists
until the stream is ready.
Upvotes: 1