【问题标题】:Can I use an asynchronous function in a stream.map()?我可以在 stream.map() 中使用异步函数吗?
【发布时间】:2020-08-25 16:31:20
【问题描述】:

是否可以将异步函数传递给 stream.map() 函数?

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
}

【问题讨论】:

    标签: firebase flutter asynchronous dart stream


    【解决方案1】:

    这是不可能的,因为map 的声明如下:

    Stream<S> map <S>(
          S convert(
              T event
            )
         )
    

    map 采用convert 类型的函数S,基本上就是使用的Stream 的类型。

    您可以使用asyncMap() 方法:

    https://api.dart.dev/stable/2.9.1/dart-async/Stream/asyncMap.html

    【讨论】:

      【解决方案2】:

      您可以使用asyncMap 执行输出到Stream 的映射,或者您可以包装您的函数并等待结果以使用带有List.map 的异步函数来获得List 结果:

      myCollection.snapshots().map((e) async => await _mappingFunc(e));
      

      另一种选择是使用async* 方法来实现Stream 输出:

      Stream<MyModel> get myStream async* {
        for (final snapshot in myCollection.snapshots()) {
          yield await _mappingFunc(snapshot);
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2014-06-14
        • 2019-08-18
        • 2022-01-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-08
        • 2018-10-04
        • 1970-01-01
        相关资源
        最近更新 更多