Observable.prototype.concatAll 似乎没有产生预期的结果 [英] Observable.prototype.concatAll does not seem to yield expected result

查看:39
本文介绍了Observable.prototype.concatAll 似乎没有产生预期的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

记住这段代码:

const Rx = require('rxjs');

var i = 3;

const obs = Rx.Observable.interval(10)
    .map(() => i++)
    .map(function(val){
        return Rx.Observable.create(obs => {
            obs.next(val)
        });
    })
    .take(10)
    .concatAll();


obs.subscribe(function(v){
    console.log(v);
});

我希望记录的结果类似于:

I would have expected the logged result to be something like:

[3,4,5,6,7,8,9,10,11,12]

即 10 个值,从 3 开始.

That is, 10 values, starting with 3.

然而,我们得到的只是

3

有人知道为什么会这样吗?

Does anybody know why that would be?

推荐答案

concatMap 将等待第一个 observable 完成,然后再订阅下一个.您忘记将 .complete() 添加到您的内部 observable,有效地让您的流只发出第一个值 3 并无限期地等待第一个流完成,然后再连接在它的旁边.

concatMap will wait for the first observable to complete before subscribing to the next. You forgot to add the .complete() to your inner observable, effectively having your stream only emit the first value 3 and waiting indefinitely for the first stream to complete before concatting the next to it.

注意;对于根据您的问题进行简单的值发射,您还可以使用 Rx.Observable.of() 而不是 Rx.Observable.create()

Note; for a simple value emission as per your question you can also use Rx.Observable.of() instead of Rx.Observable.create()

var i = 3;

const obs = Rx.Observable.interval(10)
  .map(() => i++)
  .map(val => Rx.Observable.of(val))
  .take(10)
  .concatAll();

obs.subscribe(v => console.log(v));

<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.0.3/Rx.js"></script>

这篇关于Observable.prototype.concatAll 似乎没有产生预期的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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