This feature will add the flexibility of having custom cleanup code be executed on removing an item/s.
public static ReactiveCollection<TNew> CreateDerivedCollection<T, TNew>(
this ObservableCollection<T> This,
Func<T, TNew> selector, Action<TNew> deselector = null)
{
// verbose code removed
coll_changed.Subscribe(x =>
{
switch (x.Action)
{
case NotifyCollectionChangedAction.Add:
case NotifyCollectionChangedAction.Remove:
case NotifyCollectionChangedAction.Replace:
// NB: SL4 fills in OldStartingIndex with -1 on Replace :-/
int old_index = (x.Action == NotifyCollectionChangedAction.Replace ? x.NewStartingIndex : x.OldStartingIndex);
if (x.OldItems != null)
{
foreach (object _ in x.OldItems)
{
if (deselector != null)
deselector (ret[old_index]);
ret.RemoveAt(old_index);
}
}
if (x.NewItems != null)
{
foreach (T item in x.NewItems.Cast<T>())
{
ret.Insert(x.NewStartingIndex, selector(item));
}
}
break;
case NotifyCollectionChangedAction.Reset:
if (deselector != null)
ret.Run(deselector );
ret.Clear();
break;
default:
break;
}
});