AnonymousObservable.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
  2. using System.Reactive.Disposables;
  3. namespace System.Reactive
  4. {
  5. /// <summary>
  6. /// Class to create an IObservable&lt;T&gt; instance from a delegate-based implementation of the Subscribe method.
  7. /// </summary>
  8. /// <typeparam name="T">The type of the elements in the sequence.</typeparam>
  9. public sealed class AnonymousObservable<T> : ObservableBase<T>
  10. {
  11. private readonly Func<IObserver<T>, IDisposable> _subscribe;
  12. /// <summary>
  13. /// Creates an observable sequence object from the specified subscription function.
  14. /// </summary>
  15. /// <param name="subscribe">Subscribe method implementation.</param>
  16. /// <exception cref="ArgumentNullException"><paramref name="subscribe"/> is null.</exception>
  17. public AnonymousObservable(Func<IObserver<T>, IDisposable> subscribe)
  18. {
  19. if (subscribe == null)
  20. throw new ArgumentNullException("subscribe");
  21. _subscribe = subscribe;
  22. }
  23. /// <summary>
  24. /// Calls the subscription function that was supplied to the constructor.
  25. /// </summary>
  26. /// <param name="observer">Observer to send notifications to.</param>
  27. /// <returns>Disposable object representing an observer's subscription to the observable sequence.</returns>
  28. protected override IDisposable SubscribeCore(IObserver<T> observer)
  29. {
  30. return _subscribe(observer) ?? Disposable.Empty;
  31. }
  32. }
  33. }