How to update / add elements to / in IObservable <int> dynamically?

I have an observable collection in which I want to continue to feed the objects, and they should reach the observers even after someone has subscribed to it (which, of course, is the main goal of the observable). How can I do it?

In the next program, after the subscription has passed, I want to submit 3 more numbers that should appear in the observers. How can I do it?

I don’t want to go through the route where I implement my own Observable class, implement the IObservable<int> and use the 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); } } 
+6
source share
1 answer

This is what I would 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); 

Typically, if you can observe what an additional input generates, you would need to concatenate this observable, rather than forcibly push these values ​​to the topic, but sometimes this is impractical.

+5
source

Source: https://habr.com/ru/post/908629/


All Articles