← Back to all articles

Rx – Awaiting events & observables in C#Β 5

So everyone is now using C# 5 to write asynchronous methods to await tasks right πŸ˜‰

Did you know you can also await other things? Like events & observables!?

The following code demonstrates how you can β€œawait” items being added to an observable collection.

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

namespace ConsoleApplication11
{
    class Program
    {
        private static readonly ObservableCollection Collection = new ObservableCollection();

        static void Main()
        {
            Test();
            Collection.Add(42);
        }

        public static async void Test()
        {
            Console.WriteLine("awaiting event...");
            var itemsAdded = await 
                (
                    from collectionChanged in Collection.ToNotifyCollectionChangedObservable()
                    where collectionChanged.EventArgs.Action == NotifyCollectionChangedAction.Add
                    select collectionChanged.EventArgs.NewItems
                )
                .Take(1);

            Console.WriteLine("items added;");
            foreach (var item in itemsAdded)
                Console.WriteLine(item);
        }
    }

    public static class Extensions
    {
        public static IObservable> 
            ToNotifyCollectionChangedObservable(this INotifyCollectionChanged source)
        {
            return Observable.FromEventPattern
                (h => source.CollectionChanged += h,
                h => source.CollectionChanged -= h);
        }
    }
}

Enjoy!

*UPDATE* make sure you have Rx-experimental release. The GetAwaiter method is not in the stable release yet!

Comments