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<int> Collection = new ObservableCollection<int>();

        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<EventPattern<NotifyCollectionChangedEventArgs>> 
            ToNotifyCollectionChangedObservable(this INotifyCollectionChanged source)
        {
            return Observable.FromEventPattern<NotifyCollectionChangedEventHandler, NotifyCollectionChangedEventArgs>
                (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!

 

Pop Quiz: Asynchronous Methods & Contract Errors

This is for people wanting to expand their asynchronous brains!

Pop Quiz

Here is a question for you; What will this seemly trivial program segment do?

void X()
{
    try
    {
        Y();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

async void Y()
{
    throw new NotImplementedException();
}

Before you answer, consider another question; Is there a behavioral difference between these two methods?

IEnumerable<int> J()
{
    throw new NotImplementedException();
}

IEnumerable<int> K()
{
    throw new NotImplementedException();
    yield return -1;
}

Don’t worry some Rx posts are coming soon!

Reactive Extensions utilizing 64 cores

Saw this on Facebook… welcome to the future;

image

Follow

Get every new post delivered to your Inbox.