Ejemplo n.º 1
0
        /// <summary>
        /// Call methods 'onAdd' and 'onRemove' whenever an object is added or
        /// removed from a collection. This class correctly handles both when
        /// a collection is initialized, as well as when the collection is Reset.
        /// </summary>
        /// <param name="onAdd">A method to be called when an object is added
        /// to the collection.</param>
        /// <param name="onRemove">A method to be called when an object is removed
        /// from the collection.</param>
        /// <returns>A Disposable that deactivates this behavior.</returns>
        public static IDisposable ActOnEveryObject <T>(this IReactiveCollection <T> This, Action <T> onAdd, Action <T> onRemove)
            where T : IReactiveObject
        {
            foreach (var v in This)
            {
                onAdd(v);
            }

            var changingDisp = This.Changing
                               .Where(x => x.Action == NotifyCollectionChangedAction.Reset)
                               .Subscribe(
                _ => This.ForEach(x => onRemove(x)));

            var changedDisp = This.Changed.Subscribe(x => {
                switch (x.Action)
                {
                case NotifyCollectionChangedAction.Add:
                    foreach (T v in x.NewItems)
                    {
                        onAdd(v);
                    }
                    break;

                case NotifyCollectionChangedAction.Replace:
                    foreach (T v in x.OldItems)
                    {
                        onRemove(v);
                    }
                    foreach (T v in x.NewItems)
                    {
                        onAdd(v);
                    }
                    break;

                case NotifyCollectionChangedAction.Remove:
                    foreach (T v in x.OldItems)
                    {
                        onRemove(v);
                    }
                    break;

                case NotifyCollectionChangedAction.Reset:
                    foreach (T v in This)
                    {
                        onAdd(v);
                    }
                    break;

                default:
                    break;
                }
            });

            return(Disposable.Create(() => {
                changingDisp.Dispose();
                changedDisp.Dispose();

                This.ForEach(x => onRemove(x));
            }));
        }