开发者

using Reactive Extensions to monitor IEnumerable

I'm connecting to an object that asyncronously loads开发者_如何学JAVA a collection of objects into an IEnumerable. At the time I connect, the IEnumerable may have items already in it's collection, and may add items during the lifetime of the application that I need to be notified of as they occur. As an example, it could be a bank account containing a list of bank transactions.

The challenge is this. I want to combine the processing of the initial values in the IEnumerable with any new additions. They are currently two processes. I would like to eliminate the use of NotifyCollectionChanged entirely.

I can modify the backend holding the IEnumerable. It does not need to remain as an IEnumerable if a solution to this question exists otherwise.


I would suggest that the object should not expose a IEnumerable as that is for "cold observable values", where in your case you need something which can get additional items in future also.

The best way to model this would be to use ReplaySubject<T> instead of IEnumerable. Below is an example that demonstrate the situation similar of yours:

//Function to generate the subject with future values
public static ReplaySubject<int> GetSubject()
{
    var r = new ReplaySubject<int>();
    r.OnNext(1); r.OnNext(2); r.OnNext(3);
    //Task to generate future values
    Task.Factory.StartNew(() =>
    {
        while (true)
        {
            Thread.Sleep(3000);
            r.OnNext(DateTime.Now.Second);
        }
    });
    return r;
}

Consuming code:

var sub = GetSubject();
sub.Subscribe(Console.WriteLine);

Every time anyone subscribes to sub they will get all the values that have been published in the subject till now and as well as new values that this subject generates in future


You can use Defer/Replay Operator

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜