@@ -51,37 +51,39 @@ private AsyncPublisher(Publisher<T> original, Executor executor) {
51
51
52
52
@ Override
53
53
public void subscribe (Subscriber <? super T > s ) {
54
- original . subscribe ( new AsyncSubscriber < T >( requireNonNull (s ), executor ) );
54
+ AsyncSubscriber . wrapAndSubscribe ( original , requireNonNull (s ), executor );
55
55
}
56
56
57
57
private static final class AsyncSubscriber <T > implements Subscriber <T > {
58
58
private final BlockingQueue <Object > signalQueue = new LinkedBlockingQueue <Object >();
59
59
60
- private AsyncSubscriber (final Subscriber <? super T > original , final Executor executor ) {
60
+ static <T > void wrapAndSubscribe (final Publisher <T > publisher ,
61
+ final Subscriber <? super T > targetSubscriber , final Executor executor ) {
62
+ final AsyncSubscriber <T > asyncSubscriber = new AsyncSubscriber <T >();
61
63
try {
62
64
executor .execute (new Runnable () {
63
65
@ Override
64
66
public void run () {
65
67
for (; ; ) {
66
68
try {
67
- final Object signal = signalQueue .take ();
69
+ final Object signal = asyncSubscriber . signalQueue .take ();
68
70
if (signal instanceof Cancelled ) {
69
71
return ;
70
72
} else if (signal instanceof TerminalSignal ) {
71
73
Thread .sleep (TERMINAL_DELAY_MS );
72
74
TerminalSignal terminalSignal = (TerminalSignal ) signal ;
73
75
if (terminalSignal .cause == null ) {
74
- original .onComplete ();
76
+ targetSubscriber .onComplete ();
75
77
} else {
76
- original .onError (terminalSignal .cause );
78
+ targetSubscriber .onError (terminalSignal .cause );
77
79
}
78
80
return ;
79
81
} else if (signal instanceof OnSubscribeSignal ) {
80
- original .onSubscribe (((OnSubscribeSignal ) signal ).subscription );
82
+ targetSubscriber .onSubscribe (((OnSubscribeSignal ) signal ).subscription );
81
83
} else {
82
84
@ SuppressWarnings ("unchecked" )
83
85
final T onNextSignal = ((OnNextSignal <T >) signal ).onNext ;
84
- original .onNext (onNextSignal );
86
+ targetSubscriber .onNext (onNextSignal );
85
87
}
86
88
} catch (InterruptedException ex ) {
87
89
throw new RuntimeException (ex );
@@ -90,7 +92,7 @@ public void run() {
90
92
}
91
93
});
92
94
} catch (Throwable cause ) {
93
- original .onSubscribe (new Subscription () {
95
+ targetSubscriber .onSubscribe (new Subscription () {
94
96
@ Override
95
97
public void request (long n ) {
96
98
}
@@ -99,8 +101,12 @@ public void request(long n) {
99
101
public void cancel () {
100
102
}
101
103
});
102
- original .onError (new IllegalStateException ("Executor rejected" , cause ));
104
+ targetSubscriber .onError (new IllegalStateException ("Executor rejected" , cause ));
105
+ // Publisher rejected the target subscriber and terminated it, don't continue to subscribe to avoid
106
+ // duplicate termination.
107
+ return ;
103
108
}
109
+ publisher .subscribe (asyncSubscriber );
104
110
}
105
111
106
112
@ Override
0 commit comments