19
19
import java .util .Collection ;
20
20
import java .util .List ;
21
21
import java .util .concurrent .ConcurrentLinkedQueue ;
22
+ import java .util .concurrent .atomic .AtomicBoolean ;
22
23
import java .util .concurrent .atomic .AtomicReference ;
23
24
24
25
import rx .Observable ;
@@ -371,6 +372,21 @@ public void call() {
371
372
}
372
373
373
374
}));
375
+ //need to subscribe to all the sources
376
+ for (Observable <? extends T > source : sources ) {
377
+ if (subscriber .isUnsubscribed ()) {
378
+ return ;
379
+ }
380
+ AmbSubscriber <T > ambSubscriber = new AmbSubscriber <T >(0 , subscriber , selection );
381
+ selection .ambSubscribers .add (ambSubscriber );
382
+ // check again if choice has been made so can stop subscribing
383
+ if (selection .choice .get () != null ) {
384
+ // Already chose one, the rest can be skipped and we can clean up
385
+ selection .unsubscribeOthers (selection .choice .get ());
386
+ return ;
387
+ }
388
+ source .unsafeSubscribe (ambSubscriber );
389
+ }
374
390
subscriber .setProducer (new Producer () {
375
391
376
392
@ Override
@@ -379,19 +395,21 @@ public void request(long n) {
379
395
// propagate the request to that single Subscriber that won
380
396
selection .choice .get ().requestMore (n );
381
397
} else {
382
- for (Observable <? extends T > source : sources ) {
383
- if (subscriber .isUnsubscribed ()) {
384
- break ;
385
- }
386
- AmbSubscriber <T > ambSubscriber = new AmbSubscriber <T >(n , subscriber , selection );
387
- selection .ambSubscribers .add (ambSubscriber );
388
- // possible race condition in previous lines ... a choice may have been made so double check (instead of synchronizing)
389
- if (selection .choice .get () != null ) {
390
- // Already chose one, the rest can be skipped and we can clean up
391
- selection .unsubscribeOthers (selection .choice .get ());
392
- break ;
398
+ //subscriptions already happened so propagate the request to all the
399
+ //amb subscribers
400
+ for (AmbSubscriber <T > ambSubscriber : selection .ambSubscribers ) {
401
+ if (!ambSubscriber .isUnsubscribed ()) {
402
+ // make a best endeavours check to not waste requests
403
+ // if first emission has already occurred
404
+ if (selection .choice .get () == ambSubscriber ) {
405
+ ambSubscriber .requestMore (n );
406
+ //don't need to request from other subscribers because choice has been made
407
+ //and request has gone to choice
408
+ return ;
409
+ } else {
410
+ ambSubscriber .requestMore (n );
411
+ }
393
412
}
394
- source .unsafeSubscribe (ambSubscriber );
395
413
}
396
414
}
397
415
}
0 commit comments