AddRef.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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;
  5. using System.Reactive.Disposables;
  6. namespace System.Reactive.Linq.ObservableImpl
  7. {
  8. internal class AddRef<TSource> : Producer<TSource>
  9. {
  10. private readonly IObservable<TSource> _source;
  11. private readonly RefCountDisposable _refCount;
  12. public AddRef(IObservable<TSource> source, RefCountDisposable refCount)
  13. {
  14. _source = source;
  15. _refCount = refCount;
  16. }
  17. protected override IDisposable Run(IObserver<TSource> observer, IDisposable cancel, Action<IDisposable> setSink)
  18. {
  19. var d = StableCompositeDisposable.Create(_refCount.GetDisposable(), cancel);
  20. var sink = new _(observer, d);
  21. setSink(sink);
  22. return _source.SubscribeSafe(sink);
  23. }
  24. class _ : Sink<TSource>, IObserver<TSource>
  25. {
  26. public _(IObserver<TSource> observer, IDisposable cancel)
  27. : base(observer, cancel)
  28. {
  29. }
  30. public void OnNext(TSource value)
  31. {
  32. base._observer.OnNext(value);
  33. }
  34. public void OnError(Exception error)
  35. {
  36. base._observer.OnError(error);
  37. base.Dispose();
  38. }
  39. public void OnCompleted()
  40. {
  41. base._observer.OnCompleted();
  42. base.Dispose();
  43. }
  44. }
  45. }
  46. }