首页 > 解决方案 > CombineLatest 反应式操作符是如何工作的?

问题描述

我在 Linqpad 中运行了以下代码片段:

$"[{(DateTime.Now.ToString("HH:mm:ss.fff"))}] 0 0".Dump();
Observable
    .Interval(TimeSpan.FromSeconds(3))
    .CombineLatest(Observable.Interval(TimeSpan.FromSeconds(10)), (x, y) => $"[{(DateTime.Now.ToString("HH:mm:ss.fff"))}] {x} {y}")
    .Do(Console.WriteLine).Wait();

这是我得到的结果:

[23:38:40.111] 0 0
[23:38:50.183] 2 0
[23:38:52.180] 3 0
[23:38:55.196] 4 0
[23:38:58.197] 5 0
[23:39:00.181] 5 1
[23:39:01.198] 6 1
[23:39:04.198] 7 1
[23:39:07.210] 8 1
[23:39:10.196] 8 2
[23:39:10.211] 9 2
[23:39:13.211] 10 2
[23:39:16.211] 11 2
[23:39:19.212] 12 2
[23:39:20.197] 12 3
[23:39:22.227] 13 3
[23:39:25.228] 14 3
[23:39:28.229] 15 3
[23:39:30.196] 15 4
[23:39:31.241] 16 4
[23:39:34.242] 17 4

我无法解释这个序列的开始:

  1. 为什么是第一个计算值2 0
  2. 为什么2 0开始后10秒输出?

标签: system.reactive

解决方案


来自:http ://reactivex.io/documentation/operators/combinelatest.html

结合最新

当两个 Observable 中的任何一个发出 item 时,通过指定的函数组合每个 Observable 发出的最新 item,并根据该函数的结果发出 item

也许这个修改后的代码将帮助您了解正在发生的事情:

$"[{(DateTime.Now.ToString("HH:mm:ss.fff"))}] 0 0".Dump();
Observable.Interval(TimeSpan.FromSeconds(3))
        .Do(x => $"[{(DateTime.Now.ToString("HH:mm:ss.fff"))}] {x} _".Dump())
    .CombineLatest(
        Observable.Interval(TimeSpan.FromSeconds(10))
            .Do(y => $"[{(DateTime.Now.ToString("HH:mm:ss.fff"))}] _ {y}".Dump()),
        (x, y) => $"[{(DateTime.Now.ToString("HH:mm:ss.fff"))}] {x} {y}")
    .Do(s => s.Dump())
    .Wait();

推荐阅读