AddRef.cs 1.6 KB

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