简体   繁体   中英

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

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.

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] , [AB] , [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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM