示例#1
0
        public static IDisposable ProcessEach <T>(this IObservableCollection <T> self, Action <T> func, Action <T> onRemove = null)
        {
            foreach (var item in self)
            {
                func(item);
            }
            var finalDisp  = new ListDisposable();
            var collection = new Collection <T>();

            finalDisp.Add(self.ObserveReset().Listen(unit =>
            {
                if (onRemove != null)
                {
                    foreach (var element in collection)
                    {
                        onRemove(element);
                    }
                }

                collection.Clear();
            }));
            finalDisp.Add(self.ObserveAdd().Listen(add =>
            {
                func(add.Value);
                collection.Add(add.Value);
            }));
            finalDisp.Add(self.ObserveReplace().Listen(replaceEvent =>
            {
                collection.Add(replaceEvent.NewValue);
                collection.Remove(replaceEvent.OldValue);
                func(replaceEvent.NewValue);
                if (onRemove != null)
                {
                    onRemove(replaceEvent.OldValue);
                }
            }));

            if (onRemove != null)
            {
                finalDisp.Add(self.ObserveRemove().Listen(remove =>
                {
                    onRemove(remove.Value);
                    collection.Remove(remove.Value);
                }));
            }
            return(finalDisp);
        }