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);
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With