两个流的条件配对 - Combine If in Reactive Extensions

Conditional pairing of two streams - Combine If in Reactive Extensions

我希望结合前两个序列,正如 Marble 图所描述的那样

  1. 在此示例中,不同的彩票玩家选择号码,并且 他们选择的数字由上面小点的颜色表示 第一行。
  2. 中奖号码决定时(第 2 行)
  3. 需要确定彩票中奖者(第 3 行输出)。对于彩票 winners 小点代表获胜的玩家。

期望的输出

Rx 解决方案?

你为球员选择的颜色和为数字选择的颜色让事情有点混乱。

尽管如此,这对我有用。

开始于:

var picks = new Subject<KeyValuePair<string, string>>(); // key == number, value = player
var numbers = new Subject<string>();

然后按数字构建一系列选秀字典:

var scanned =
    picks
        .Scan(new Dictionary<string, string>(), (d, kvp) =>
        {
            // You need a new dictionary each time
            var d2 = new Dictionary<string, string>(d);
            d2[kvp.Key] = kvp.Value;
            return d2;
        });

现在合并使用 .Switch():

var query =
    scanned
        .Select(d =>
            numbers.Select(n => new
            {
                player = d[n],
                number = n
            }))
        .Switch();

就是这样。

这是运行它的代码:

query.Subscribe(x => Console.WriteLine(x));

picks.OnNext(new KeyValuePair<string, string>("Brown", "Blue"));
picks.OnNext(new KeyValuePair<string, string>("Grey", "Green"));
picks.OnNext(new KeyValuePair<string, string>("Red", "Black"));
picks.OnNext(new KeyValuePair<string, string>("Grey", "Yellow"));
numbers.OnNext("Red");
numbers.OnNext("Brown");
picks.OnNext(new KeyValuePair<string, string>("Grey", "Black"));
picks.OnNext(new KeyValuePair<string, string>("Red", "White"));
numbers.OnNext("Red");

这是我得到的结果: