Zip运算符何时发出错误

Zip运算符何时发出错误

本文介绍了[Rx.js] Zip运算符何时发出错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习并遇到一个问题 zip 运算符:

I am learning Rx.js and have one problem with zip operator:

    var error =Rx.Observable.throw('Oop!');
    var age$ = Rx.Observable.concat(Rx.Observable.of(21,22,23),error);
    var sex$ = Rx.Observable.of("male","male","female","female");
    var name$ = Rx.Observable.of("jack","john","james","lucy");
    var example = Rx.Observable.zip(age$,sex$,name$,(age,sex,name)=>{ return {age,sex,name} });

我订阅示例来源并打印一些消息:

and i subscribe the example source and print some message:

    example.subscribe({
        next: (value) => { console.log(value); },
        error: (err) => { console.log('Error: ' + err); },
        complete: () => { console.log('complete'); }
    });

输出不是我的预期:

{age:21,sex:"male",name:"jack"}
{age:22,sex:"male",name:"john"}
{age:23,sex:"female",name:"james"}
error

但只有一行没有值输出

    error

阅读但是当 zip 运算符发出时没有解释章节错误

read the offical doc but no chapter explained when the zip operator emit error.

任何人都可以帮忙吗?非常感谢。

Can anyone help?thx very much.

推荐答案

您会立即看到错误,因为您传递的第一个observable会同步发出其值。 (其他可观察量也会同步发出它们的值,但在这种情况下无关紧要。)

You see the error straight away because the first observable that you pass emits its values synchronously. (The other observables emit their values synchronously, too, but that does not matter in this scenario.)

zip 按顺序订阅传递的observable并按照它们的传递顺序。在订阅第一个observable时, zip 同步接收所有observable的值和连接错误。它然后发出它自己的错误并完成。

zip subscribes to the passed observables one by one and in the order in which they are passed. Upon subscribing to the first observable, zip synchronously receives all of the observable's values and the concatenated error. It then emits its own error and is done.

如果指定可选的scheduler参数 - 以便observables异步发出它们的值 - 你会看到你期望的行为:

If you specify the optional scheduler argument - so that the observables emit their values asynchronously - you will see the behaviour you were expecting:

var age$ = Rx.Observable.concat(
  Rx.Observable.of(21, 22, 23, Rx.Scheduler.async),
  Rx.Observable.throw("Oop!", Rx.Scheduler.async)
);

var sex$ = Rx.Observable.of(
  "male", "male", "female", "female",
  Rx.Scheduler.async
);

var name$ = Rx.Observable.of(
  "jack", "john", "james", "lucy",
  Rx.Scheduler.async
);

var zipped$ = Rx.Observable.zip(
  age$, sex$, name$,
  (age, sex, name) => ({ age, sex, name })
);
zipped$.subscribe(
  (value) => console.log(value),
  (error) => console.log(error),
  () => console.log("complete")
);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://unpkg.com/rxjs@5/bundles/Rx.min.js"></script>

这篇关于[Rx.js] Zip运算符何时发出错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 04:25