4个稳定版本
| 1.1.2 | 2023年8月13日 | 
|---|---|
| 1.1.1 | 2023年2月24日 | 
| 1.0.0 | 2023年2月22日 | 
#10 in #yield
每月44次下载
8KB
71 行
combine-latest
将两个流合并成一个新的流,该流返回每个输入流的最新值的元组。受Rx的combineLatest启发。
use async_stream::stream;
use combine_latest::combine_latest;
fn combine_weather_data_streams(
    temperature: impl Stream<i32>,
    weather_notes: impl Stream<String>,
) -> Stream<String> {
    stream! {
        for await (t, n) in combine_latest(temperature, weather_notes) {
            yield format!("Temperature {t}°, note: {n}");
        }
    }
}
combine_latest将不会在其输入流返回值之前返回其第一个元组。如果您需要尽快获取项目,有一个combine_latest_opt函数,它会返回(Option<T1>, Option<T2>)元组。
随着时间在temperature和weather_notes流中传入值,combine_latest和combine_latest_opt将返回值如下
| 时间 | 温度 | 天气备注 | combine_latest | combine_latest_opt | 
|---|---|---|---|---|
| 0 | 25 | (Some(25), None) | ||
| 1 | 26 | (Some(26), None) | ||
| 2 | 能见度低 | (26, "能见度低") | (Some(26), Some("能见度低")) | |
| 3 | 雾 | (26, "雾") | (Some(26), Some("雾")) | |
| 4 | 25 | (25, "雾") | (Some(25), Some("雾")) | 
由于相同的输入值可能在输出流中返回多次,因此输入流返回的项目必须实现Clone。
对于没有实现Clone的类型,可以使用函数map_latest
fn combine_weather_data_streams(
    temperature: impl Stream<NonCloneTemperature>,
    weather_notes: impl Stream<String>,
) -> Stream<String> {
    stream! {
        for await output in map_latest(
            temperature,
            weather_notes,
            |t, n| format!("Temperature {t}°, note: {n}"),
        ) {
            yield output;
        }
    }
}
将添加到您的项目中:cargo add combine-latest
依赖关系
~570–760KB
~14K SLoC