简体   繁体   English

未完成的 observable 的 forkJoin 替代方案?

[英]A forkJoin alternative for uncompleted observables?

constructor(
    private route: ActivatedRoute,
    private http: Http
){
    // Observe parameter changes
    let paramObs = route.paramMap;

    // Fetch data once
    let dataObs = http.get('...');

    // Subscribe to both observables,
    // use both resolved values at the same level
}

Is there something similar to forkJoin that triggers whenever a parameter change is emitted?是否有类似于forkJoin东西在发出参数更改时触发? forkJoin only works when all observables have completed. forkJoin仅在所有 observable 完成后才有效。

I just need to avoid callback hell, any alternative that complies is welcome.我只需要避免回调地狱,欢迎任何符合要求的替代方案。

There are several options:有几种选择:

  1. Use take(1) with forkJoin() to complete each source Observable:使用take(1)forkJoin()来完成每个源 Observable:

     forkJoin(o1$.take(1), o2$.take(1))
  2. Use zip() and take(1) to emit only when all source Observables have emitted the same number of items:使用zip()take(1)仅在所有源 Observable 发出相同数量的项目时才发出:

     zip(o1$, o2$).take(1)
  3. Use combineLatest() to emit when any of the source Observables emit:当任何源 Observables 发出时,使用combineLatest()发出:

     combineLatest(o1$, o2$)

Jan 2019: Updated for RxJS 6 2019 年 1 月:针对 RxJS 6 更新

In addition to the other answer, consider using Observable.concat() which will handle each observable in sequence.除了其他答案之外,请考虑使用Observable.concat() ,它将按顺序处理每个 observable。 Here's an example:下面是一个例子:

const getPostOne$ = Rx.Observable.timer(3000).mapTo({id: 1});
const getPostTwo$ = Rx.Observable.timer(1000).mapTo({id: 2});

Rx.Observable.concat(getPostOne$, getPostTwo$).subscribe(res => console.log(res));

A good article outlining 6 operators you should know .一篇很好的文章,概述了您应该知道的 6 个运算符

A small trick to avoid breaking of observable subscriptions if any one of the observable fails.如果任何一个 observable 失败,一个避免破坏 observable 订阅的小技巧。


import { throwError, of, forkJoin } from "rxjs";
import { catchError, take } from "rxjs/operators";

//emits an error with specified value on subscription
const observables$ = [];
const observableThatWillComplete$ = of(1, 2, 3, 4, 5).pipe(take(1));

const observableThatWillFail$ = throwError(
  "This is an error hence breaking the stream"
).pipe(catchError((error) => of(`Error Catched: ${error}`)));

observables$.push(observableThatWillComplete$, observableThatWillFail$);

forkJoin(observables$).subscribe(responses => {
  console.log("Subscribed");
  console.log(responses);
});

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

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