-
Notifications
You must be signed in to change notification settings - Fork 751
/
Switch.cs
139 lines (114 loc) · 3.98 KB
/
Switch.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT License.
// See the LICENSE file in the project root for more information.
using System.Reactive.Disposables;
namespace System.Reactive.Linq.ObservableImpl
{
internal sealed class Switch<TSource> : Producer<TSource, Switch<TSource>._>
{
private readonly IObservable<IObservable<TSource>> _sources;
public Switch(IObservable<IObservable<TSource>> sources)
{
_sources = sources;
}
protected override _ CreateSink(IObserver<TSource> observer) => new(observer);
protected override void Run(_ sink) => sink.Run(_sources);
internal sealed class _ : Sink<IObservable<TSource>, TSource>
{
private readonly object _gate = new();
public _(IObserver<TSource> observer)
: base(observer)
{
}
private SerialDisposableValue _innerSerialDisposable;
private bool _isStopped;
private ulong _latest;
private bool _hasLatest;
protected override void Dispose(bool disposing)
{
if (disposing)
{
_innerSerialDisposable.Dispose();
}
base.Dispose(disposing);
}
public override void OnNext(IObservable<TSource> value)
{
ulong id;
lock (_gate)
{
id = unchecked(++_latest);
_hasLatest = true;
}
var innerObserver = new InnerObserver(this, id);
_innerSerialDisposable.Disposable = innerObserver;
innerObserver.SetResource(value.SubscribeSafe(innerObserver));
}
public override void OnError(Exception error)
{
lock (_gate)
{
ForwardOnError(error);
}
}
public override void OnCompleted()
{
lock (_gate)
{
DisposeUpstream();
_isStopped = true;
if (!_hasLatest)
{
ForwardOnCompleted();
}
}
}
private sealed class InnerObserver : SafeObserver<TSource>
{
private readonly _ _parent;
private readonly ulong _id;
public InnerObserver(_ parent, ulong id)
{
_parent = parent;
_id = id;
}
public override void OnNext(TSource value)
{
lock (_parent._gate)
{
if (_parent._latest == _id)
{
_parent.ForwardOnNext(value);
}
}
}
public override void OnError(Exception error)
{
lock (_parent._gate)
{
Dispose();
if (_parent._latest == _id)
{
_parent.ForwardOnError(error);
}
}
}
public override void OnCompleted()
{
lock (_parent._gate)
{
Dispose();
if (_parent._latest == _id)
{
_parent._hasLatest = false;
if (_parent._isStopped)
{
_parent.ForwardOnCompleted();
}
}
}
}
}
}
}
}