I have a Class, MyClass
that implements INotifyPropertyChanged
and has some properties that implement PropertyChanged
. When MyClass.MyProperty
changes, PropertyChanged
fires as expected. Another class contains a SortedList<MyClass>
.I've tried merging the events into a single observable in the class that contains the SortedSet<MyClass>
and subscribing to it, but it doesn't seem to ever have any events. Here's what I'm trying:
Observable.Merge(MySortedList.ToObservable())
.Subscribe(evt => Console.WriteLine("{0} changed", evt.MyProperty));
What I'm trying to get is a single observable that contains all of the events from every item in my SortedList<MyClass>
. I've tried using ObservableCollection instead, but that doesn't change anything, nor would it be expected to, really, since it doesn't fire collectionchanged when a property of a contained item changes, anyway. I can listen to individual elements in SortedList<MyClass>
and see the PropertyChanged event fire, but what I want is a single Observable that contains a stream of ALL of the PropertyChanged events from all of the elements in SortedList<MyClass>
.
It seems like this should be something fairly easy to do using Rx, but I can't seem to figure out how.
Assuming from your description that you're able to provide this:
You can use this to merge the property observables into a single observable:
If you find this insufficient, you'll need to give more details about why you can't provide
observableProperties
.For example, if I had a class like this:
I could create
observableProperties
like this:I have produced an article for the RxCookBook on this subject that you can find here https://github.com/LeeCampbell/RxCookbook/blob/master/Model/CollectionChange.md Further article on PropertyChange notification is here https://github.com/LeeCampbell/RxCookbook/blob/master/Model/PropertyChange.md
It solves what you need by aggregating up the changes from an
ObservableCollection<T>
. By using theObservableCollection<T>
you also get notifications when items are added or removed from the collection.If you dont want to use the
ObservableCollection<T>
(i.e. you only want to track properties at a given snapshot of the collection) then you will need to do something else. First I assume you have anINoftifyPropertyChanged
toIObservable<T>
extension method or you are just going to use the standard event toIObservable<T>
methods.Next you can project the List of values into a list of change sequences i.e.
IEnumerable<T>
toIEumerable<IObserable<T>>
. This allows you to useObservable.Merge
to flatten the list of changes in to a single stream of changes.Here is a sample if you dont want to use the link above:
Which will output: