Rx:用于从 Observable 流中获取第一个和最新值的运算符 [英] Rx: operator for getting first and most recent value from an Observable stream

查看:23
本文介绍了Rx:用于从 Observable 流中获取第一个和最新值的运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于基于 Rx 的更改跟踪解决方案,我需要一个操作员,它可以为我提供可观察序列中的第一个和最新的项目.

For an Rx based change tracking solution I am in need of an operator which can get me the first and most recent item in an observable sequence.

我将如何编写生成以下弹珠图的 Rx 运算符(注意:括号仅用于排列项目...我不确定如何最好地在文本中表示这一点):

How would I write an Rx operator that produces the following marble diagram (Note: the brackets are used just to lineup the items...I'm not sure how best to represent this in text):

     xs:---[a  ]---[b  ]-----[c  ]-----[d  ]---------|
desired:---[a,a]---[a,b]-----[a,c]-----[a,d]---------| 

推荐答案

使用与@Wilka 相同的命名,您可以使用以下扩展名,这有点不言自明:

Using the same naming as @Wilka you can use the below extension which is somewhat self-explanatory:

public static IObservable<TResult> FirstAndLatest<T, TResult>(this IObservable<T> source, Func<T,T,TResult> func)
{
    var published = source.Publish().RefCount();
    var first = published.Take(1);        
    return first.CombineLatest(published, func);
}

请注意,它不一定返回 Tuple,而是为您提供在结果上传递选择器函数的选项.这使其与底层主要操作 (CombineLatest) 保持一致.这显然很容易改变.

Note that it doesn't necessarily return a Tuple, but rather gives you the option of passing a selector function on the result. This keeps it in line with the underlying primary operation (CombineLatest). This is obviously easily changed.

用法(如果您想在结果流中使用元组):

Usage (if you want Tuples in the resulting stream):

Observable.Interval(TimeSpan.FromSeconds(0.1))
          .FirstAndLatest((a,b) => Tuple.Create(a,b))
          .Subscribe(Console.WriteLine);

这篇关于Rx:用于从 Observable 流中获取第一个和最新值的运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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