watchStream<T extends Object, R> function
watchStream subscribes to the Stream returned by select and returns
an AsyncSnapshot with the latest received data from the Stream
Whenever new data is received it triggers a rebuild.
When you call watchStream a second time on the same Stream it will
return the last received data but not subscribe another time.
To be able to use watchStream inside a build function we have to pass
initialValue so that it can return something before it has received the first data
if select returns a different Stream than on the last call, watchStream
will cancel the previous subscription and subscribe to the new stream.
preserveState determines then if the new initial value should be the last
value of the previous stream or again initialValue
If you want to observe a Stream that is not registered in get_it you can
pass it as target.
if you pass null as select, T or target has to be a Stream<R>.
instanceName is the optional name of the instance if you registered it
with a name in get_it.
getIt is the optional instance of get_it to use if you don't want to use the
default one. 99% of the time you won't need this.
Implementation
AsyncSnapshot<R> watchStream<T extends Object, R>(
Stream<R> Function(T)? select, {
T? target,
R? initialValue,
bool preserveState = true,
bool allowStreamChange = false,
String? instanceName,
GetIt? getIt,
}) {
assert(_activeWatchItState != null,
'watchStream can only be called inside a build function within a WatchingWidget or a widget using the WatchItMixin');
final getItInstance = getIt ?? di;
final parentObject = target ?? getItInstance<T>(instanceName: instanceName);
// Validate target type when no select function is provided
if (select == null && parentObject is! Stream<R>) {
throw ArgumentError(
'When no select function is provided, target must be a Stream<$R>. '
'Got: ${parentObject.runtimeType}');
}
return _activeWatchItState!.watchStream(
parentOrStream: parentObject,
initialValue: initialValue,
instanceName: instanceName,
preserveState: preserveState,
selector: select,
allowStreamChange: allowStreamChange);
}