Combining 2 arrays in correct sequence using Rx.js

2019-07-24 22:38发布

I am a bit new Rx.js and trying to get this scenario working.Basically I need combine the following two sequences such that they merge into a single array, where the obs1 elements are always before obs2 elements,

var obs1 = Rx.Observable.create(function(observer){
setTimeout(function(){
 observer.next([1,2,3]);
  }, 1000);
});

var obs2 = Rx.Observable.create(function(observer){
setTimeout(function(){
 observer.next([4,5,6]);
  }, 10);
});

I am not going "complete" any of these observables by the way.

I want the final output in my subscription to be [1,2,3,4,5,6]. I tried, concat, flatMap in few variations but did not help. I could possibly, create another observable, and create an array by pushing the elements of obs1, then of obs2 and then calling "next", but that does not feel the right way to do this...

Could you please assist in understanding what operators might work here?

标签: rxjs
1条回答
劫难
2楼-- · 2019-07-24 23:16

First of all, the "RxJs" way of writing your code would be :

var obs1 = Rx.Observable.of([1, 2, 3]).delay(1000);
var obs2 = Rx.Observable.of([4, 5, 6]).delay(10);

Then, you might use concat operator :

obs1
  .combineLatest(obs2)
  .map(([rslt1, rslt2]) => [...rslt1, ...rslt2])
  .do(arr => console.log(arr)) // 1, 2, 3, 4 ,5, 6
  .subscribe()

Here's a working Plunkr : https://plnkr.co/edit/tMceIDiLzYIfVemuZka9?p=preview

查看更多
登录 后发表回答