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.
Richard Szalay
source share