I need to subscribe to a property of an object in a list. I found this example (https://stackoverflow.com/a/18770397/3954928), which works perfect, but if I add a new element to the list, it does not work. Any solution? Thank you!
EDIT
IDisposable subscription =
Observable
.FromEventPattern
<NotifyCollectionChangedEventHandler, NotifyCollectionChangedEventArgs>(
x => MyList.CollectionChanged += x,
x => MyList.CollectionChanged -= x)
.Where(x => x.EventArgs.Action == NotifyCollectionChangedAction.Add)
.SelectMany(x => x.EventArgs.NewItems.Cast<MyCustomClass>())
.SelectMany(x =>
{
CallMethodWhenAddItem(x);
return x.OnPropertyChange(nameof(x.MyCustomProperty));
})
.Subscribe(x =>
// x is PropertyChangedEventArgs, not MyCustomClass
if (x.MyCustomProperty == "SomeValue") {
RunAction();
}
});
public static IObservable<PropertyChangedEventArgs> OnPropertyChange<T>(this T currentSource, string propertyName)
where T : INotifyPropertyChanged
{
return
Observable
.FromEventPattern
<PropertyChangedEventHandler, PropertyChangedEventArgs>(
eventHandler => eventHandler.Invoke,
x => currentSource.PropertyChanged += x,
x => currentSource.PropertyChanged -= x)
.Where(x => x.EventArgs.PropertyName == propertyName)
.Select(x => x.EventArgs);
}
Could you guide me a little with the following questions?
1) What is the difference of using "eventHandler => eventHandler.Invoke" and not using it. Many examples on the internet use it and others do not. And I really do not see the difference.
2) How I unsubscribe from a property that was added "dynamically". Just remove it from the list?
Thx!