简体   繁体   中英

Rx JS Subscribe Observer to multiple Observables

Scratching the surface of Rx JS I ve ended up with the following snippet:

    var observer1 = Rx.Observer.create(
         function (x) {
             console.log('Next: ' + x);
         },
         function (err) {
             console.log('Error: ' + err);
         },
         function () {
             console.log('Completed');
         }
     );  

     var observer2 = Rx.Observer.create(
         function (x) {
             console.log('Next: ' + x); 
         },  
         function (err) {
             console.log('Error: ' + err);   
         },  
         function () {
             console.log('Completed');   
         }   
     );  


     var source1 = Rx.Observable.return(1);
     var source2 = Rx.Observable.return(2);

     var subscription1 = source1.subscribe(observer1);
     var subscription2 = source2.subscribe(observer1);

OUTPUT: Next: 1 Completed

JS BIN Code reference: http://goo.gl/DiHdWu

Subscribing the same observer to both streams only yields data from the first one. However when subscribing the other observer things go as expected. Can someone please explain what is going on?

     var subscription1 = source1.subscribe(observer1);
     var subscription2 = source2.subscribe(observer2);

OUTPUT: Next: 1 Completed Next: 2 Completed

Yes, an observer can listen to multiple Observables but not the way you are trying to use. This can be achieved by using Merge , concat operators. Code reference jsbin .

Why your code didn't work?

We get an IObserver for every call of Observer.create . It will ignore any future calls of OnNext once OnError or OnComplete is called.

When we use one observer to subscribe multiple Observables, after the first observable terminates / completes (ie when it triggers OnError / OnCompleted) the observer will not work for any further subscribed observables. Because the termination message from the first observable will cause the observer to ignore messages from any further subscribed observables.

For your problem to work, you need to use operators like merge , concat which will use multiple observers internally and do not pass completion messages(OnError/OnCompleted) from any observables except the last Observable to the outer observer.

//Triggers observer1 for both observables(source1 & source2)
var subscription = source1.concat(source2).subscribe(observer1);

//Triggers observer2 for both observables(source1 & source2)
var subscription = source1.merge(source2).subscribe(observer2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM