Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rxjs: Does forkJoin need at least one call to next to complete?

Tags:

rxjs

rxjs5

I have two observables which I would like to forkJoin:

  var goodObservable = Rx.Observable.create( function(observer){
    observer.next('something');
    observer.complete();
  });

  var badObservable = Rx.Observable.create( function(observer){
    observer.complete();
  });


  var forkJoinedObservable = Rx.Observable.forkJoin([goodObservable, badObservable]);  

  forkJoinedObservable.subscribe(function(results){
    console.log(results);
  });

One of those observables only calls complete. Now I have found that the forkJoined observables never gets triggered. I will have to call observer.next() in the badObservable in order to make the subscription on forkJoin to be executed.

My expected behaviour would be that the forkJoin-subscribes would be executed with an array containing just one item: ['something']

Is this a bug, or did I not understand the concept correctly?

I have made a plunkr for this: https://plnkr.co/edit/QaA9DwyWAmTGbthvguPK?p=preview

like image 216
Tobias Gassmann Avatar asked Oct 20 '25 11:10

Tobias Gassmann


1 Answers

forkJoin() emits the last emitted item from each observable. There's no item to emit in this case, so the operator doesn't emit.

A pragmatic solution would be to call .startsWith(defaultValue) on each observable, so forkJoin() can complete as well.

var goodObservable = Rx.Observable.create( function(observer){
  observer.next('something');
  observer.complete();
});

var badObservable = Rx.Observable.create( function(observer){
  observer.complete();
}).startWith(null);


var forkJoinedObservable = Rx.Observable.forkJoin([goodObservable, badObservable]);  

forkJoinedObservable.subscribe(function(results){
  console.log(results);
});

About emitting values just for the observables that have emitted, this wouldn't work, because then you wouldn't know which one didn't emit. Of course, it could have emitted null. But given this is achievable by combining operators, I don't think it's gonna change.

like image 187
André Werlang Avatar answered Oct 23 '25 02:10

André Werlang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!