Observer in the collection

I am taking the first steps in the Rx frameworks on .net 4. I am trying to observe a collection like List<int> or Dictionary<x,x> . and when the item is added to the collection, it will write its ToString() in the console.

any ideas? or some code examples thanks

+6
c # system.reactive
source share
2 answers

List<T> and Dictionary<TKey, TValue> not observed (they do not raise events when they change), so there is nothing for Rx.

For List you can use ObservableCollection<T> , but you will need to wrap its events in order to use it from Rx. The following is an example of using extension methods:

 public static class ObservableCollectionExtensions { public static IObservable<IEvent<NotifyCollectionChangedEventArgs>> GetObservableChanges<T>(this ObservableCollection<T> collection) { return Observable.FromEvent< NotifyCollectionChangedEventHandler, NotifyCollectionChangedArgs>( h => new NotifyCollectionChangedEventHandler(h), h => collection.CollectionChanged += h, h => collection.CollectionChanged -= h ); } public static IObservable<T> GetObservableAddedValues<T>( this ObservableCollection<T> collection) { return collection.GetObservableChanges() .Where(evnt => evnt.EventArgs.Action == NotifyCollectionChangedAction.Add) .SelectMany(evnt => evnt.EventArgs.NewItems.Cast<T>()); } } 

I have included an additional helper that expands the elements just added as IObservable<T> , which you can use as follows:

 ObservableCollection<int> collection = new ObservableCollection<int>(new int[] { 1, 2, 3 }); collection.GetObservableAddedValues().Subscribe( i => Console.WriteLine("{0} was added", i) ); 

There is no observable dictionary in the structure, although the ObservableDictionary codeplex project seems to fill this gap, and I'm sure it can be wrapped in a similar way.

+9
source share

Use the ReactiveCollection from ReactiveUI :

 var c = new ReactiveCollection<int>(); c.Changed.Subscribe(x => Console.Writeln(x.Value); c.Add(1); 
+1
source share

All Articles