Finally.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 Finally<TSource> : Producer<TSource>
  10. {
  11. private readonly IObservable<TSource> _source;
  12. private readonly Action _finallyAction;
  13. public Finally(IObservable<TSource> source, Action finallyAction)
  14. {
  15. _source = source;
  16. _finallyAction = finallyAction;
  17. }
  18. protected override IDisposable Run(IObserver<TSource> observer, IDisposable cancel, Action<IDisposable> setSink)
  19. {
  20. var sink = new _(this, observer, cancel);
  21. setSink(sink);
  22. return sink.Run();
  23. }
  24. class _ : Sink<TSource>, IObserver<TSource>
  25. {
  26. private readonly Finally<TSource> _parent;
  27. public _(Finally<TSource> parent, IObserver<TSource> observer, IDisposable cancel)
  28. : base(observer, cancel)
  29. {
  30. _parent = parent;
  31. }
  32. public IDisposable Run()
  33. {
  34. var subscription = _parent._source.SubscribeSafe(this);
  35. return Disposable.Create(() =>
  36. {
  37. try
  38. {
  39. subscription.Dispose();
  40. }
  41. finally
  42. {
  43. _parent._finallyAction();
  44. }
  45. });
  46. }
  47. public void OnNext(TSource value)
  48. {
  49. base._observer.OnNext(value);
  50. }
  51. public void OnError(Exception error)
  52. {
  53. base._observer.OnError(error);
  54. base.Dispose();
  55. }
  56. public void OnCompleted()
  57. {
  58. base._observer.OnCompleted();
  59. base.Dispose();
  60. }
  61. }
  62. }
  63. }
  64. #endif