gpt4 book ai didi

flutter - 如何在 Dart 中制作 Future.wait 的 Stream 版本?

转载 作者:行者123 更新时间:2023-12-03 03:11:23 27 4
gpt4 key购买 nike

我要跑Future.wait()在某些网络调用上,以便它们可以同时运行。我想进一步加快速度,以便在结果可用时返回结果,以便我可以开始显示它们。我想只是对 Future.wait 的一个小修改call 将是我所需要的,但不幸的是,它在内部使用私有(private)类。有没有更好的方法来实现这一点?
Future.wait dart documentation

最佳答案

您可以使用 Stream.fromFutures constructor

The stream reports the results of the futures on the stream in theorder in which the futures complete. Each future provides either adata event or an error event, depending on how the future completes.

If some futures have already completed when Stream.fromFutures iscalled, their results will be emitted in some unspecified order.

When all futures have completed, the stream is closed.

Stream<int> streamingInts = Stream.fromFutures([
Future.delayed(Duration(seconds: 1), () => 1),
Future.delayed(Duration(seconds: 2), () => 2),
]);

await for (final i in streamingInts) {
print(i);
}
我的真实用例 - 显示加载所需的时间比预期的要多
  • 如果我真正的 api 调用很快结束,我只会产生 LoadedState 并停止收听流
  • 如果我真正的 api 调用太慢,特殊 Future.delayed 将触发特殊状态 LoadingTakesTooLongState
  •       Stream<BlocState> loadingStates = Stream.fromFutures([
    Future.delayed(_kTooSlowDelay, () => LoadingTakesTooLongState()),
    _loadData(),
    ]);

    await for (var state in loadingStates) {
    yield state;
    if (state is LoadedState) break;
    }

    Future<LoadedState> _loadData() ...

    关于flutter - 如何在 Dart 中制作 Future.wait 的 Stream 版本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62722114/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com