AnonymousObservable.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the Apache 2.0 License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Reactive.Disposables;
  5. namespace System.Reactive
  6. {
  7. /// <summary>
  8. /// Class to create an <see cref="IObservable{T}"/> instance from a delegate-based implementation of the <see cref="IObservable{T}.Subscribe(IObserver{T})"/> method.
  9. /// </summary>
  10. /// <typeparam name="T">The type of the elements in the sequence.</typeparam>
  11. public sealed class AnonymousObservable<T> : ObservableBase<T>
  12. {
  13. private readonly Func<IObserver<T>, IDisposable> _subscribe;
  14. /// <summary>
  15. /// Creates an observable sequence object from the specified subscription function.
  16. /// </summary>
  17. /// <param name="subscribe"><see cref="IObservable{T}.Subscribe(IObserver{T})"/> method implementation.</param>
  18. /// <exception cref="ArgumentNullException"><paramref name="subscribe"/> is <c>null</c>.</exception>
  19. public AnonymousObservable(Func<IObserver<T>, IDisposable> subscribe)
  20. {
  21. if (subscribe == null)
  22. throw new ArgumentNullException(nameof(subscribe));
  23. _subscribe = subscribe;
  24. }
  25. /// <summary>
  26. /// Calls the subscription function that was supplied to the constructor.
  27. /// </summary>
  28. /// <param name="observer">Observer to send notifications to.</param>
  29. /// <returns>Disposable object representing an observer's subscription to the observable sequence.</returns>
  30. protected override IDisposable SubscribeCore(IObserver<T> observer)
  31. {
  32. return _subscribe(observer) ?? Disposable.Empty;
  33. }
  34. }
  35. }