使用 Rx.js 按正确顺序组合 2 个数组 [英] Combining 2 arrays in correct sequence using Rx.js

查看:53
本文介绍了使用 Rx.js 按正确顺序组合 2 个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点新 Rx.js 并试图让这个场景工作.基本上我需要组合以下两个序列,以便它们合并成一个数组,其中 obs1 元素总是在 obs2 元素之前,

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);
});

顺便说一下,我不会完成"任何这些 observable.

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

我希望订阅中的最终输出为 [1,2,3,4,5,6].我尝试了几种变体,concat,flatMap,但没有帮助.我可以创建另一个 observable,然后通过推送 obs1 的元素,然后推送 obs2 的元素然后调用next"来创建一个数组,但这感觉不是正确的方法......

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"方式是:

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);

然后,您可以使用 concat 运算符:

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()

这是一个有效的 Plunkr:https://plnkr.co/edit/tMceIDiLzYIfVemuZka9?p=预览

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

这篇关于使用 Rx.js 按正确顺序组合 2 个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆