Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I update/add items in/to an IObservable<int> dynamically?

I have an observable collection to which I want to keep feeding objects and they should reach observers even after someone has subscribed to it (which ofcourse is the main aim of an observable). How do I do it?

In the following program, after the subscription has happened I want to feed in 3 more numbers which should reach observers. How do I do this?

I don't want to go via the route where I implement my own Observable class by implementing IObservable<int> and use Publish method? Is there any other way to achieve this?

public class Program
{
    static void Main(string[] args)
    {
        var collection = new List<double> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        var observableCollection = collection.ToObservable();
        observableCollection.Subscribe(OnNext);
        //now I want to add 100, 101, 102 which should reach my observers
        //I know this wont' work
        collection.Add(100);
        collection.Add(101);
        collection.Add(102);
        Console.ReadLine();
    }

    private static void OnNext(double i)
    {
        Console.WriteLine("OnNext - {0}", i);
    }
}
like image 701
P.K Avatar asked Feb 16 '12 15:02

P.K


1 Answers

This is what I'd do:

    var subject = new Subject<double>();
    var collection = new List<double> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    var observableCollection = collection
        .ToObservable()
        .Concat(subject); //at the end of the original collection, add the subject
    observableCollection.Subscribe(OnNext);

    //now I want to add 100, 101, 102 which should reach my observers
    subject.OnNext(100);
    subject.OnNext(101);
    subject.OnNext(102);

Generally, if you can observe whatever is producing the additional input, you'd want to concat that observable, rather than imperatively pushing these values into a subject, but sometimes that's not practical.

like image 89
Anderson Imes Avatar answered Oct 25 '22 04:10

Anderson Imes