FirstAsync.cs 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT License.
  3. // See the LICENSE file in the project root for more information.
  4. namespace System.Reactive.Linq.ObservableImpl
  5. {
  6. internal static class FirstAsync<TSource>
  7. {
  8. internal sealed class Sequence : Producer<TSource, Sequence._>
  9. {
  10. private readonly IObservable<TSource> _source;
  11. public Sequence(IObservable<TSource> source)
  12. {
  13. _source = source;
  14. }
  15. protected override _ CreateSink(IObserver<TSource> observer) => new _(observer);
  16. protected override void Run(_ sink) => sink.Run(_source);
  17. internal sealed class _ : IdentitySink<TSource>
  18. {
  19. private bool _found;
  20. public _(IObserver<TSource> observer)
  21. : base(observer)
  22. {
  23. }
  24. public override void OnNext(TSource value)
  25. {
  26. _found = true;
  27. ForwardOnNext(value);
  28. ForwardOnCompleted();
  29. }
  30. public override void OnCompleted()
  31. {
  32. if (!_found)
  33. {
  34. try
  35. {
  36. throw new InvalidOperationException(Strings_Linq.NO_ELEMENTS);
  37. }
  38. catch (Exception e)
  39. {
  40. ForwardOnError(e);
  41. }
  42. }
  43. }
  44. }
  45. }
  46. internal sealed class Predicate : Producer<TSource, Predicate._>
  47. {
  48. private readonly IObservable<TSource> _source;
  49. private readonly Func<TSource, bool> _predicate;
  50. public Predicate(IObservable<TSource> source, Func<TSource, bool> predicate)
  51. {
  52. _source = source;
  53. _predicate = predicate;
  54. }
  55. protected override _ CreateSink(IObserver<TSource> observer) => new _(_predicate, observer);
  56. protected override void Run(_ sink) => sink.Run(_source);
  57. internal sealed class _ : IdentitySink<TSource>
  58. {
  59. private readonly Func<TSource, bool> _predicate;
  60. private bool _found;
  61. public _(Func<TSource, bool> predicate, IObserver<TSource> observer)
  62. : base(observer)
  63. {
  64. _predicate = predicate;
  65. }
  66. public override void OnNext(TSource value)
  67. {
  68. bool b;
  69. try
  70. {
  71. b = _predicate(value);
  72. }
  73. catch (Exception ex)
  74. {
  75. ForwardOnError(ex);
  76. return;
  77. }
  78. if (b)
  79. {
  80. _found = true;
  81. ForwardOnNext(value);
  82. ForwardOnCompleted();
  83. }
  84. }
  85. public override void OnCompleted()
  86. {
  87. if (!_found)
  88. {
  89. try
  90. {
  91. throw new InvalidOperationException(Strings_Linq.NO_MATCHING_ELEMENTS);
  92. }
  93. catch (Exception e)
  94. {
  95. ForwardOnError(e);
  96. }
  97. }
  98. }
  99. }
  100. }
  101. }
  102. }