If.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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.Collections.Generic;
  7. using System.Reactive.Disposables;
  8. namespace System.Reactive.Linq.ObservableImpl
  9. {
  10. class If<TResult> : Producer<TResult>, IEvaluatableObservable<TResult>
  11. {
  12. private readonly Func<bool> _condition;
  13. private readonly IObservable<TResult> _thenSource;
  14. private readonly IObservable<TResult> _elseSource;
  15. public If(Func<bool> condition, IObservable<TResult> thenSource, IObservable<TResult> elseSource)
  16. {
  17. _condition = condition;
  18. _thenSource = thenSource;
  19. _elseSource = elseSource;
  20. }
  21. public IObservable<TResult> Eval()
  22. {
  23. return _condition() ? _thenSource : _elseSource;
  24. }
  25. protected override IDisposable Run(IObserver<TResult> observer, IDisposable cancel, Action<IDisposable> setSink)
  26. {
  27. var sink = new _(this, observer, cancel);
  28. setSink(sink);
  29. return sink.Run();
  30. }
  31. class _ : Sink<TResult>, IObserver<TResult>
  32. {
  33. private readonly If<TResult> _parent;
  34. public _(If<TResult> parent, IObserver<TResult> observer, IDisposable cancel)
  35. : base(observer, cancel)
  36. {
  37. _parent = parent;
  38. }
  39. public IDisposable Run()
  40. {
  41. var result = default(IObservable<TResult>);
  42. try
  43. {
  44. result = _parent.Eval();
  45. }
  46. catch (Exception exception)
  47. {
  48. base._observer.OnError(exception);
  49. base.Dispose();
  50. return Disposable.Empty;
  51. }
  52. return result.SubscribeSafe(this);
  53. }
  54. public void OnNext(TResult value)
  55. {
  56. base._observer.OnNext(value);
  57. }
  58. public void OnError(Exception error)
  59. {
  60. base._observer.OnError(error);
  61. base.Dispose();
  62. }
  63. public void OnCompleted()
  64. {
  65. base._observer.OnCompleted();
  66. base.Dispose();
  67. }
  68. }
  69. }
  70. }
  71. #endif