简体   繁体   English

[Rx.js] Zip运算符何时发出错误?

[英][Rx.js]when does Zip operator emit error?

I am learning Rx.js and have one problem with zip operator: 我正在学习Rx.js并且有一个zip运算符的问题:

    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源并打印一些消息:

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

the out put is not what i expected: 输出不是我所期望的:

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

but just one line with no value output : 但只有一行with no value output

    error

read the offical doc but no chapter explained when the zip operator emit error . 阅读官方文档,zip操作符发出error时没有解释章节。

Can anyone help?thx very much. 任何人都可以帮忙吗?thx非常。

You see the error straight away because the first observable that you pass emits its values synchronously. 您会立即看到错误,因为您传递的第一个observable会同步发出其值。 (The other observables emit their values synchronously, too, but that does not matter in this scenario.) (其他可观察量也同步发出它们的值,但在这种情况下无关紧要。)

zip subscribes to the passed observables one by one and in the order in which they are passed. zip按照传递的顺序逐个订阅传递的observable。 Upon subscribing to the first observable, zip synchronously receives all of the observable's values and the concatenated error. 在订阅第一个observable时, zip同步接收所有可观察的值和连接的错误。 It then emits its own error and is done. 然后它会发出自己的错误并完成。

If you specify the optional scheduler argument - so that the observables emit their values asynchronously - you will see the behaviour you were expecting: 如果指定可选的scheduler参数 - 以便observables异步发出它们的值 - 您将看到您期望的行为:

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM