Debian Codegraph @

external/rx/Rx/NET/Source/System.Reactive.Linq/Reactive/Linq/Observable/FirstAsync.cs

raw
1 // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
2
3 #if !NO_PERF
4 using System;
5
6 namespace System.Reactive.Linq.ObservableImpl
7 {
8 class FirstAsync<TSource> : Producer<TSource>
9 {
10 private readonly IObservable<TSource> _source;
11 private readonly Func<TSource, bool> _predicate;
12 private readonly bool _throwOnEmpty;
13
14 public FirstAsync(IObservable<TSource> source, Func<TSource, bool> predicate, bool throwOnEmpty)
15 {
16 _source = source;
17 _predicate = predicate;
18 _throwOnEmpty = throwOnEmpty;
19 }
20
21 protected override IDisposable Run(IObserver<TSource> observer, IDisposable cancel, Action<IDisposable> setSink)
22 {
23 if (_predicate != null)
24 {
25 var sink = new FirstAsyncImpl(this, observer, cancel);
26 setSink(sink);
27 return _source.SubscribeSafe(sink);
28 }
29 else
30 {
31 var sink = new _(this, observer, cancel);
32 setSink(sink);
33 return _source.SubscribeSafe(sink);
34 }
35 }
36
37 class _ : Sink<TSource>, IObserver<TSource>
38 {
39 private readonly FirstAsync<TSource> _parent;
40
41 public _(FirstAsync<TSource> parent, IObserver<TSource> observer, IDisposable cancel)
42 : base(observer, cancel)
43 {
44 _parent = parent;
45 }
46
47 public void OnNext(TSource value)
48 {
49 base._observer.OnNext(value);
50 base._observer.OnCompleted();
51 base.Dispose();
52 }
53
54 public void OnError(Exception error)
55 {
56 base._observer.OnError(error);
57 base.Dispose();
58 }
59
60 public void OnCompleted()
61 {
62 if (_parent._throwOnEmpty)
63 {
64 base._observer.OnError(new InvalidOperationException(Strings_Linq.NO_ELEMENTS));
65 }
66 else
67 {
68 base._observer.OnNext(default(TSource));
69 base._observer.OnCompleted();
70 }
71
72 base.Dispose();
73 }
74 }
75
76 class FirstAsyncImpl : Sink<TSource>, IObserver<TSource>
77 {
78 private readonly FirstAsync<TSource> _parent;
79
80 public FirstAsyncImpl(FirstAsync<TSource> parent, IObserver<TSource> observer, IDisposable cancel)
81 : base(observer, cancel)
82 {
83 _parent = parent;
84 }
85
86 public void OnNext(TSource value)
87 {
88 var b = false;
89
90 try
91 {
92 b = _parent._predicate(value);
93 }
94 catch (Exception ex)
95 {
96 base._observer.OnError(ex);
97 base.Dispose();
98 return;
99 }
100
101 if (b)
102 {
103 base._observer.OnNext(value);
104 base._observer.OnCompleted();
105 base.Dispose();
106 }
107 }
108
109 public void OnError(Exception error)
110 {
111 base._observer.OnError(error);
112 base.Dispose();
113 }
114
115 public void OnCompleted()
116 {
117 if (_parent._throwOnEmpty)
118 {
119 base._observer.OnError(new InvalidOperationException(Strings_Linq.NO_MATCHING_ELEMENTS));
120 }
121 else
122 {
123 base._observer.OnNext(default(TSource));
124 base._observer.OnCompleted();
125 }
126
127 base.Dispose();
128 }
129 }
130 }
131 }
132 #endif