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

1

6

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);
    }
}
Camilla answered 16/2, 2012 at 15:31 Comment(1)
What do you want the IObservable<double> to do if you remove items?Take
A
5

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.

Ametropia answered 16/2, 2012 at 19:2 Comment(1)
it was not clear that Subscribe(OnNext) and subject.OnNext(100) are not really the same reference. The former is any method to call as an item comes in. The latter is an Rx method to notify subscribed observers a new observable event has arrived in the sequence.Endocrinology

© 2022 - 2024 — McMap. All rights reserved.