当流产生一定价值时,创造流之外的未来

时间:2019-09-09 11:11:26

标签: flutter dart stream

我有一个产生CallEvent对象的流。我想调用此流,但是我对一个特定事件感兴趣,并希望将来使用它。这可能吗?

我要实现的伪代码:

final Stream<CallEvent> aStreamOfEvents = repo.getEvents();

// However of this stream im only interested in the `ResponseEvent`

final Future<ResponseEvent> response = 
       aStreamOfEvents.filter((event) { event is ResponseEvent}).toFuture()

这可能吗?如果可以,怎么办?

1 个答案:

答案 0 :(得分:3)

final response = aStreamOfEvents.firstWhere((e) => e is ResponseEvent);

response在上方Future<CallEvent>,因此,如果您需要Future<ResponseEvent>,则需要类似以下内容:

final response = aStreamOfEvent
    .firstWhere((e) => e is ResponseEvent)
    .then((e) => e as ResponseEvent);

或者,如果您使用package:stream_transform

final response = aStreamOfEvent
    .transform(whereType<ResponseEvent>())
    .first

如果Stream在关闭时没有发出ResponseEvent,那么在所有这些情况下,将来都会出错。具体错误将取决于您选择的模式。