如何 return 基于另一个流事件的流

How to return a stream based on another stream's event

我想return一个流基于另一个流的value/event。

例如,如果我有 2 个流,stream1 和 stream2,我想创建一个函数,根据 stream1 的值,returns 作为流 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 这样的任何额外的包依赖,只是纯飞镖?

看起来 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