Is it possible to pass an asynchronous function into a stream.map() function?
final CollectionReference myCollection =
FirebaseFirestore.instance.collection('foo');
Future<Stream<MyModel>> get myStream async {
// incorrect code, but I want to do something like this
return await myCollection.snapshots().map(_mappingFunc);
}
Future<MyModel> _mappingFunc(QuerySnapshot snapshot) async {
// some async code
}
That's not possible, since the declaration of the map
is the following:
Stream<S> map <S>(
S convert(
T event
)
)
map
takes a convert
function which is of type S
, basically the type of the Stream
used.
You can use the asyncMap()
method:
https://api.dart.dev/stable/2.9.1/dart-async/Stream/asyncMap.html
You can either use asyncMap to perform the mapping which outputs to a Stream
or you can wrap your function and await the result to use an asynchronous function with List.map to get a List
result:
myCollection.snapshots().map((e) async => await _mappingFunc(e));
Another option is to use an async*
method to achieve a Stream
output:
Stream<MyModel> get myStream async* {
for (final snapshot in myCollection.snapshots()) {
yield await _mappingFunc(snapshot);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With