Home > Code Samples > Rx – Remove from an ObservableCollection after a specified time

Rx – Remove from an ObservableCollection after a specified time

September 27th, 2010 Leave a comment Go to comments

There was an interesting question on StackOverflow today that leads to another good example of the power of Reactive Extensions. The question was “How can I remove an item from an ObservableCollection some fixed amount of time after it was added?” With Rx it’s extremely simple! Here’s a quick console application demonstrating how to do it.

using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Threading;

namespace Test_App
{
    class Program
    {
        static void Main(string[] args)
        {
            var oc = new ObservableCollection<int>();

            var disposer =
             Observable
              .FromEvent<NotifyCollectionChangedEventArgs>(oc, "CollectionChanged")
              .Where(e => e.EventArgs.Action == NotifyCollectionChangedAction.Add)
              .Delay(TimeSpan.FromSeconds(5))
              .Subscribe(
                  e =>
                  {
                      foreach (int i in e.EventArgs.NewItems)
                      {
                          Console.WriteLine(string.Format("Removing item {0} at {1:HH:mm:ss}", i, DateTime.Now));
                          oc.Remove(i);
                      }
                  });

            for (int i = 1; i < 10; i++)
            {
                Console.WriteLine(string.Format("Added item {0} at {1:HH:mm:ss}", i, DateTime.Now));
                oc.Add(i);
                Thread.Sleep(1000);
            }

            Console.WriteLine("Press any key to exit..");
            Console.ReadKey(true);

            disposer.Dispose();
        }
    }
}

And here’s the output:

Added item 1 at 10:21:44
Added item 2 at 10:21:45
Added item 3 at 10:21:46
Added item 4 at 10:21:47
Added item 5 at 10:21:48
Added item 6 at 10:21:49
Removing item 1 at 10:21:49
Removing item 2 at 10:21:50
Added item 7 at 10:21:50
Added item 8 at 10:21:51
Removing item 3 at 10:21:51
Added item 9 at 10:21:52
Removing item 4 at 10:21:52
Press any key to exit..
Removing item 5 at 10:21:53
Removing item 6 at 10:21:54
Removing item 7 at 10:21:55
Removing item 8 at 10:21:56
Removing item 9 at 10:21:57

Pretty simple huh?

Categories: Code Samples Tags:
  1. Jason
    September 30th, 2010 at 23:15 | #1

    Wow, I’m impressed with your grasp of RX. You make it look easy. Not saying it’s hard but it does take a bit to wrap your head around it for most folks.

  1. No trackbacks yet.