Sink.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. #if !NO_PERF
  5. using System.Threading;
  6. namespace System.Reactive
  7. {
  8. /// <summary>
  9. /// Base class for implementation of query operators, providing a lightweight sink that can be disposed to mute the outgoing observer.
  10. /// </summary>
  11. /// <typeparam name="TSource">Type of the resulting sequence's elements.</typeparam>
  12. /// <remarks>Implementations of sinks are responsible to enforce the message grammar on the associated observer. Upon sending a terminal message, a pairing Dispose call should be made to trigger cancellation of related resources and to mute the outgoing observer.</remarks>
  13. internal abstract class Sink<TSource> : IDisposable
  14. {
  15. protected internal volatile IObserver<TSource> _observer;
  16. private IDisposable _cancel;
  17. public Sink(IObserver<TSource> observer, IDisposable cancel)
  18. {
  19. _observer = observer;
  20. _cancel = cancel;
  21. }
  22. public virtual void Dispose()
  23. {
  24. _observer = NopObserver<TSource>.Instance;
  25. Interlocked.Exchange(ref _cancel, null)?.Dispose();
  26. }
  27. public IObserver<TSource> GetForwarder() => new _(this);
  28. private sealed class _ : IObserver<TSource>
  29. {
  30. private readonly Sink<TSource> _forward;
  31. public _(Sink<TSource> forward)
  32. {
  33. _forward = forward;
  34. }
  35. public void OnNext(TSource value)
  36. {
  37. _forward._observer.OnNext(value);
  38. }
  39. public void OnError(Exception error)
  40. {
  41. _forward._observer.OnError(error);
  42. _forward.Dispose();
  43. }
  44. public void OnCompleted()
  45. {
  46. _forward._observer.OnCompleted();
  47. _forward.Dispose();
  48. }
  49. }
  50. }
  51. }
  52. #endif