I have a firebase snapshot StreamProvider
final poiChangesProvider = StreamProvider.autoDispose((ref) {
return db.collection(POI.colPois)
.withConverter<POI>(
fromFirestore: (snapshot, _) => ...,
toFirestore: (poi, _) => ...)
.snapshots();
});
When I ref.watch/listen to it I get all the POIs and then a stream of changes, as expected. But when I ref.watch it from multiple places, the first one to watch gets all the initial data, while all other watchers only receive the following updates.
How can I make a provider that caches and returns the last streamed data to new listeners?
The riverpod docs for StreamProvider state that it caches the latest value emitted by the stream, ensuring that if a listener is added after an event is emitted, the listener will still have immediate access to the most up-to-date event.
But I have not been able to make this happen.
StreamProvider keeping track of the last value and offering it to new listeners is the default behavior – assuming your listener is ref.watch
.
If you are talking about ref.listen
, it has an optional fireImmediately
parameter:
// Inside providers
ref.listen(
provider,
fireImmediately: true,
(previous, next) => print('value $next'),
);
// Inside consumers
ref.listenManual(
provider,
fireImmediately: true,
(previous, next) => print('value $next'),
);