PushToPullAdapter.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. using System;
  5. using System.Collections;
  6. using System.Collections.Generic;
  7. using System.Reactive.Disposables;
  8. namespace System.Reactive.Linq.ObservableImpl
  9. {
  10. abstract class PushToPullAdapter<TSource, TResult> : IEnumerable<TResult>
  11. {
  12. private readonly IObservable<TSource> _source;
  13. public PushToPullAdapter(IObservable<TSource> source)
  14. {
  15. _source = source;
  16. }
  17. IEnumerator IEnumerable.GetEnumerator()
  18. {
  19. return GetEnumerator();
  20. }
  21. public IEnumerator<TResult> GetEnumerator()
  22. {
  23. var d = new SingleAssignmentDisposable();
  24. var res = Run(d);
  25. d.Disposable = _source.SubscribeSafe(res);
  26. return res;
  27. }
  28. protected abstract PushToPullSink<TSource, TResult> Run(IDisposable subscription);
  29. }
  30. abstract class PushToPullSink<TSource, TResult> : IObserver<TSource>, IEnumerator<TResult>, IDisposable
  31. {
  32. private readonly IDisposable _subscription;
  33. public PushToPullSink(IDisposable subscription)
  34. {
  35. _subscription = subscription;
  36. }
  37. public abstract void OnNext(TSource value);
  38. public abstract void OnError(Exception error);
  39. public abstract void OnCompleted();
  40. public abstract bool TryMoveNext(out TResult current);
  41. private bool _done;
  42. public bool MoveNext()
  43. {
  44. if (!_done)
  45. {
  46. var current = default(TResult);
  47. if (TryMoveNext(out current))
  48. {
  49. Current = current;
  50. return true;
  51. }
  52. else
  53. {
  54. _done = true;
  55. _subscription.Dispose();
  56. }
  57. }
  58. return false;
  59. }
  60. public TResult Current
  61. {
  62. get;
  63. private set;
  64. }
  65. object IEnumerator.Current
  66. {
  67. get { return Current; }
  68. }
  69. public void Reset()
  70. {
  71. throw new NotSupportedException();
  72. }
  73. public void Dispose()
  74. {
  75. _subscription.Dispose();
  76. }
  77. }
  78. }