如何结合一个缓慢移动的可观察到的与最近的快速移动的可观察的值 [英] How to combine a slow moving observable with the most recent value of a fast moving observable

查看:116
本文介绍了如何结合一个缓慢移动的可观察到的与最近的快速移动的可观察的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个朋友问我这一点 - 我认为这是一个很好的问题,所以我在这里重新张贴它,我的回答:

A friend asked me this - I thought it was a good question so I am reposting it and my answer here:

我有这两个流:

var slowSource = Observable.Interval(TimeSpan.FromSeconds(1));
var fastSource = Observable.Interval(TimeSpan.FromMilliseconds(100));

和我想要让我产生含有
输出对它们结合起来 - 从slowSource
的下一个值 - 从fastSource最新值

and I’d like to combine them so that I produce output pairs which contain - The next value from slowSource - The most recent value from fastSource

我只想从slowSource每个值一个输出对。例如,前三个输出值可能看起来是这样的:

I only want one output pair per value from slowSource. For example, the first three output values might look something like this:

0,8
1,18,
2,28

一个加盟让我接近,但我最终每多个输出slowSource(由于该持续时间重叠的方式,我猜):

A join gets me close but I end up with more than one output per slowSource (due to the way that the durations overlap, I guess):

var qry = slowSource.Join(
          right: fastSource,
          leftDurationSelector: i => fastSource,
          rightDurationSelector: j => fastSource,
          resultSelector: (l, r) => {return new {L = l, R = r};})

.Subscribe(Console.WriteLine);

.Subscribe(Console.WriteLine);

使用群组加入和选择产生输出看起来八九不离十:

Using a GroupJoin and a Select produces output that looks about right:

var qry2 = slowSource.GroupJoin(
              right: fastSource,
              leftDurationSelector: i => fastSource,
              rightDurationSelector: j => fastSource,
              resultSelector: (l, r) => {return new {L= l, R = r};}
              )
          .Select(async item => {
            return new {L = item.L, R = await item.R.FirstAsync()};})
          .Subscribe(Console.WriteLine);



不过,这并不觉得自己是一个伟大的方式;必须有一个使用其他组合子做的东西像这样一个简单的方式更好的方法。有没有?

However, this doesn’t feel like a great approach; there must be a better way that uses the other combinators to do stuff like this in a simpler way. Is there?

推荐答案

这个怎么样超载邮编它结合了的IObservable 的IEnumerable 。它使用MostRecent()来获得一个流作为枚举的最新值的样本。

How about this overload of Zip which combines an IObservable with an IEnumerable. It uses MostRecent() to get a sample of the latest value of a stream as the enumerable.

slowSource.Zip(fastSource.MostRecent(0), (l,r) => new {l,r})

这篇关于如何结合一个缓慢移动的可观察到的与最近的快速移动的可观察的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆