Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use an asynchronous function in a stream.map()?

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
}

like image 575
Sharon Avatar asked Sep 17 '25 05:09

Sharon


2 Answers

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

like image 189
Peter Haddad Avatar answered Sep 19 '25 20:09

Peter Haddad


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);
  }
}
like image 43
Ben Konyi Avatar answered Sep 19 '25 21:09

Ben Konyi