0

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

例如,如果我有 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?

4

1 回答 1

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
于 2021-11-27T20:17:39.003 回答