Do.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. namespace System.Reactive.Linq.ObservableImpl
  5. {
  6. class Do<TSource> : Producer<TSource>
  7. {
  8. private readonly IObservable<TSource> _source;
  9. private readonly Action<TSource> _onNext;
  10. private readonly Action<Exception> _onError;
  11. private readonly Action _onCompleted;
  12. public Do(IObservable<TSource> source, Action<TSource> onNext, Action<Exception> onError, Action onCompleted)
  13. {
  14. _source = source;
  15. _onNext = onNext;
  16. _onError = onError;
  17. _onCompleted = onCompleted;
  18. }
  19. protected override IDisposable Run(IObserver<TSource> observer, IDisposable cancel, Action<IDisposable> setSink)
  20. {
  21. var sink = new _(this, observer, cancel);
  22. setSink(sink);
  23. return _source.SubscribeSafe(sink);
  24. }
  25. class _ : Sink<TSource>, IObserver<TSource>
  26. {
  27. private readonly Do<TSource> _parent;
  28. public _(Do<TSource> parent, IObserver<TSource> observer, IDisposable cancel)
  29. : base(observer, cancel)
  30. {
  31. _parent = parent;
  32. }
  33. public void OnNext(TSource value)
  34. {
  35. try
  36. {
  37. _parent._onNext(value);
  38. }
  39. catch (Exception ex)
  40. {
  41. base._observer.OnError(ex);
  42. base.Dispose();
  43. return;
  44. }
  45. base._observer.OnNext(value);
  46. }
  47. public void OnError(Exception error)
  48. {
  49. try
  50. {
  51. _parent._onError(error);
  52. }
  53. catch (Exception ex)
  54. {
  55. base._observer.OnError(ex);
  56. base.Dispose();
  57. return;
  58. }
  59. base._observer.OnError(error);
  60. base.Dispose();
  61. }
  62. public void OnCompleted()
  63. {
  64. try
  65. {
  66. _parent._onCompleted();
  67. }
  68. catch (Exception ex)
  69. {
  70. base._observer.OnError(ex);
  71. base.Dispose();
  72. return;
  73. }
  74. base._observer.OnCompleted();
  75. base.Dispose();
  76. }
  77. }
  78. }
  79. }
  80. #endif