Defer.cs 2.2 KB

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