Combining 2 arrays in correct sequence using Rx.js

China☆狼群 提交于 2019-12-11 09:52:04

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/42859848/combining-2-arrays-in-correct-sequence-using-rx-js

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!