How to retrieve lifetime operations of a sequence generator using Rx?

拥有回忆 提交于 2019-12-11 07:53:01

问题


I need way to retrieve all the objects previously generated by a sequence, alongside the new ones, when I'm notified of changes on it, using Rx. I think this is uncommon, since most systems will just want the unprocessed entries, but my situation needs the whole set of values, old and new, to work.

Is it possible to achieve this somehow? I couldn't find any similar examples and no method seem to do that.


回答1:


You can use the Scan extension method for this.

IObservable<T> source = ...;
IObservable<List<T>> history = source
    .Scan(new List<T>(), (list, item) => { list.Add(item); return list; });

If the source emits the tokens A, B, C,
then the history emits the tokens [A], [A B], [A, B, C] respectively.

If you don't want all emitted values from history to be the same List<T>, you can slightly modify the call to Scan:

IObservable<List<T>> history = source
    .Scan(new List<T>(), (list, item) => list.Concat(new[]{ item }).ToList());


来源:https://stackoverflow.com/questions/18622805/how-to-retrieve-lifetime-operations-of-a-sequence-generator-using-rx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!