如何将依赖于另一个流的流映射到依赖于两个流的新模型?

How to map a stream that depends on another stream to a new model depending on both streams?

我有 2 个 Firestore 流,其中第二个依赖于第一个。我想发出依赖于来自两个流的数据的新模型。

在伪代码中你可以这样想:

// 1st stream emits some device data
final streamA = client.device(id: 0); // Stream<DeviceData>

// 2nd stream emits some metadata for the above device type
final streamB = client.deviceMetadata(type: device.type); // Stream<DeviceMetadata>

// and finally I want to receive stream of combined device (device data + metadata)
final combinedObject = Device.from(deviceData, deviceMetadata);

但是,在访问源流中的值时,我找不到将一个流映射到另一个流的有效方法。例如 .map() 我想写:

return client.device('deviceId')
   .map((device) => client.deviceMetadata(type: device.type))
   .map((deviceMetadata) => Device.from(???, deviceMetadata));

问题当然是我不知道如何在第二个map()中访问device

我可以使用什么流转换或 rxdart 扩展来实现它?

您可以使用 rxdart 库将多个流合并为一个流https://pub.dev/documentation/rxdart/latest/rx/CombineLatestStream-class.html

好的,经过一些调整我想我找到了解决方案

// get the initial stream
final deviceStream = client.device(id: id);

// create new stream depending on the first one
final deviceTypeStream = deviceStream.flatMap( // make sure to flatten the stream so that it's not Stream<Stream<..>>
  (device) => client.deviceMetadata(type: device.type),
);

// use withLatestFrom to capture the latest value from the deviceTypeStream
// and create desired object out of that

return deviceTypeStream.withLatestFrom<DeviceData, Device>(
  deviceStream,
  (deviceType, device) => Device(device, deviceType),
);