【问题标题】:How to return a stream based on another stream's event如何根据另一个流的事件返回一个流
【发布时间】:2022-01-05 06:46:08
【问题描述】:

我想根据另一个流的值/事件返回一个流。

例如,如果我有 2 个流,stream1 和 stream2,我想创建一个函数,它根据 stream1 的值作为流返回 stream2 或 null。我该怎么做?

我尝试映射 stream1 并根据事件生成 stream2,但它不起作用。我也听不到stream1,基于事件yield stream2。

Stream<Data1?> getStream1() async* {
  // yield stream1
}

Stream<Data2?> getStream2(dynamic value) async* {
  //yield stream2 based on value
}

Stream<Data2?> getStream12() async* {
  final stream1 = getStream1();
  // not working
  yield* stream1.map((event) => event == null ? null : getStream2(event.var));
  // I also tried await for, but it has a strange behaviour
  // if I listen to the stream after (it's inconsistent)
  await for (var event in stream1) {
    if (event == null) {
      yield null;
    } else {
      yield* getStream2(event.var);
    } 
  }
}

是否有任何解决方案,最好不要像 rxdart 这样的任何额外的包依赖项,只是纯 dart?

【问题讨论】:

  • 您的await for 代码看起来正确。什么不适合你?你得到什么错误?
  • @Irn 我第一次运行它,它工作,然后它停止工作。比如,假设我输入了stream1: value1 -&gt; null -&gt; value2getStream12() 更改为value1,然后为null,然后它不会再次更改为value2
  • 这听起来更像是getStream2 的问题,而不是await for 循环的问题。尝试检查 getStream2 在调用之间是否没有缓存或重用某些内容。

标签: dart dart-async dart-stream


【解决方案1】:

看起来await for 必须工作......

你可以试试这个吗?

Stream<int> getStream1() async* {
  yield 1;
  await Future.delayed(Duration(seconds: 1));
  yield null;
  await Future.delayed(Duration(seconds: 1));
  yield 2;
  await Future.delayed(Duration(seconds: 1));
}

Stream<int> getStream2(dynamic value) async* {
  yield value;
  await Future.delayed(Duration(seconds: 1));
  yield value;
  await Future.delayed(Duration(seconds: 1));
}

Stream<int> getStream12() {
  return getStream1().asyncExpand(
    (event) => event == null ? Stream.value(null) : getStream2(event),
  );
}

void main() {
  getStream12().listen(print);
}

输出:

1
1
null
2
2

【讨论】:

  • 这确实有效。
  • 感谢您查看此内容。 @鬼
猜你喜欢
  • 2019-08-24
  • 1970-01-01
  • 1970-01-01
  • 2021-11-20
  • 1970-01-01
  • 2023-01-29
  • 2012-12-08
  • 2021-09-15
  • 2011-06-22
相关资源
最近更新 更多