If.cs 2.3 KB

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