Finally.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
  2. #if !NO_PERF
  3. using System;
  4. using System.Reactive.Disposables;
  5. namespace System.Reactive.Linq.ObservableImpl
  6. {
  7. class Finally<TSource> : Producer<TSource>
  8. {
  9. private readonly IObservable<TSource> _source;
  10. private readonly Action _finallyAction;
  11. public Finally(IObservable<TSource> source, Action finallyAction)
  12. {
  13. _source = source;
  14. _finallyAction = finallyAction;
  15. }
  16. protected override IDisposable Run(IObserver<TSource> observer, IDisposable cancel, Action<IDisposable> setSink)
  17. {
  18. var sink = new _(this, observer, cancel);
  19. setSink(sink);
  20. return sink.Run();
  21. }
  22. class _ : Sink<TSource>, IObserver<TSource>
  23. {
  24. private readonly Finally<TSource> _parent;
  25. public _(Finally<TSource> parent, IObserver<TSource> observer, IDisposable cancel)
  26. : base(observer, cancel)
  27. {
  28. _parent = parent;
  29. }
  30. public IDisposable Run()
  31. {
  32. var subscription = _parent._source.SubscribeSafe(this);
  33. return Disposable.Create(() =>
  34. {
  35. try
  36. {
  37. subscription.Dispose();
  38. }
  39. finally
  40. {
  41. _parent._finallyAction();
  42. }
  43. });
  44. }
  45. public void OnNext(TSource value)
  46. {
  47. base._observer.OnNext(value);
  48. }
  49. public void OnError(Exception error)
  50. {
  51. base._observer.OnError(error);
  52. base.Dispose();
  53. }
  54. public void OnCompleted()
  55. {
  56. base._observer.OnCompleted();
  57. base.Dispose();
  58. }
  59. }
  60. }
  61. }
  62. #endif