2
2
3
3
import java .util .ArrayList ;
4
4
5
+ import javax .management .NotificationListener ;
6
+
7
+ import rx .Notification ;
5
8
import rx .Observer ;
9
+ import rx .operators .NotificationLite ;
6
10
7
11
/**
8
12
* Enforce single-threaded, serialized, ordered execution of onNext, onCompleted, onError.
@@ -22,21 +26,7 @@ public class SerializedObserver<T> implements Observer<T> {
22
26
private boolean emitting = false ;
23
27
private boolean terminated = false ;
24
28
private ArrayList <Object > queue = new ArrayList <Object >();
25
-
26
- private static Sentinel NULL_SENTINEL = new Sentinel ();
27
- private static Sentinel COMPLETE_SENTINEL = new Sentinel ();
28
-
29
- private static class Sentinel {
30
-
31
- }
32
-
33
- private static class ErrorSentinel extends Sentinel {
34
- final Throwable e ;
35
-
36
- ErrorSentinel (Throwable e ) {
37
- this .e = e ;
38
- }
39
- }
29
+ private NotificationLite <T > on = NotificationLite .instance ();
40
30
41
31
public SerializedObserver (Observer <? super T > s ) {
42
32
this .actual = s ;
@@ -61,7 +51,7 @@ public void onCompleted() {
61
51
}
62
52
} else {
63
53
// someone else is already emitting so just queue it
64
- queue .add (COMPLETE_SENTINEL );
54
+ queue .add (on . completed () );
65
55
}
66
56
}
67
57
if (canEmit ) {
@@ -97,7 +87,7 @@ public void onError(final Throwable e) {
97
87
} else {
98
88
// someone else is already emitting so just queue it ... after eliminating the queue to shortcut
99
89
queue .clear ();
100
- queue .add (new ErrorSentinel (e ));
90
+ queue .add (on . error (e ));
101
91
}
102
92
}
103
93
if (canEmit ) {
@@ -131,11 +121,7 @@ public void onNext(T t) {
131
121
}
132
122
} else {
133
123
// someone else is already emitting so just queue it
134
- if (t == null ) {
135
- queue .add (NULL_SENTINEL );
136
- } else {
137
- queue .add (t );
138
- }
124
+ queue .add (on .next (t ));
139
125
}
140
126
}
141
127
if (canEmit ) {
@@ -168,19 +154,7 @@ public void drainQueue(ArrayList<Object> list) {
168
154
return ;
169
155
}
170
156
for (Object v : list ) {
171
- if (v != null ) {
172
- if (v instanceof Sentinel ) {
173
- if (v == NULL_SENTINEL ) {
174
- actual .onNext (null );
175
- } else if (v == COMPLETE_SENTINEL ) {
176
- actual .onCompleted ();
177
- } else if (v instanceof ErrorSentinel ) {
178
- actual .onError (((ErrorSentinel ) v ).e );
179
- }
180
- } else {
181
- actual .onNext ((T ) v );
182
- }
183
- }
157
+ on .accept (actual , v );
184
158
}
185
159
}
186
160
}
0 commit comments