Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
AsObservable() extension method for Prism's event aggregator
using System;
using Microsoft.Practices.Prism.Events;
// ReSharper disable CheckNamespace
namespace Microsoft.Practices.Prism.Events
// ReSharper restore CheckNamespace
{
public static class CompositePresentationEventExtensions
{
public static IObservable<TEventArgs> AsObservable<TEventArgs>(this CompositePresentationEvent<TEventArgs> @event)
{
return new CompositePresentationEventObservable<TEventArgs>(@event);
}
}
public class CompositePresentationEventObservable<TEventArgs> : IObservable<TEventArgs>
{
private readonly CompositePresentationEvent<TEventArgs> @event;
public CompositePresentationEventObservable(CompositePresentationEvent<TEventArgs> @event)
{
if (@event == null) throw new ArgumentNullException("event");
this.@event = @event;
}
public IDisposable Subscribe(IObserver<TEventArgs> observer)
{
return new CompositePresentationEventSubscription<TEventArgs>(@event, observer);
}
}
public class CompositePresentationEventSubscription<TEventArgs> : IDisposable
{
private readonly IObserver<TEventArgs> observer;
private readonly CompositePresentationEvent<TEventArgs> @event;
public CompositePresentationEventSubscription(CompositePresentationEvent<TEventArgs> @event, IObserver<TEventArgs> observer)
{
if (@event == null) throw new ArgumentNullException("event");
if (observer == null) throw new ArgumentNullException("observer");
this.@event = @event;
this.observer = observer;
@event.Subscribe(observer.OnNext, true);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
@event.Unsubscribe(observer.OnNext);
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~CompositePresentationEventSubscription()
{
Dispose(false);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment