Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rxjs returning different Observable depending on answer from first

I have a function which accesses two Observables and returns an Observable.

At first the first Observable is subscribed. Depending on its answer a second Observable has to be subscribed (also passing a value from first Observable to it) or not. But in any case an Observable should be returned from the function. If the condition determines the second Observable has to be queried, than of course the returned Observable should only complete once the second Observable has completed. In the other case the returned Observable completes when the first Observable completes.

So far I've got this:

private load(): Observable<boolean> {
    return this.accessControl.map((res: any) => {
        if (res.accessGranted) {
            this.dataService.getData(res.id).subscribe((v: number) => {
                this.value = v;
            }, () => {
                this.value = null;
                this.showErrorMessage();
            });
        } else {
            this.value = null;
        }
        return true;
    })
    .first();
}

The returned Observable is a mapped version of the first. However I've so far failed to wait for the second Observable and return a mapped version of it when the if clause evaluates to true.

Update

Based on answer by LLai I came up with this now:

private load(): Observable<boolean> {
    return this.accessControl.flatMap((res: any) => {
        if (res.accessGranted) {
            return this.dataService.getData(res.id)
            .catch((err) => {
                this.value = null;
                this.showErrorMessage();
                return Observable.throw(err);
            })
            .map((v: number) => {
                this.value = v;
                return true;
            });
        } else {
            this.value = null;
            return Observable.of(null);
        }
    })
    .first();
}
like image 426
daign Avatar asked Nov 21 '25 05:11

daign


1 Answers

you want the flatMap function http://reactivex.io/documentation/operators/flatmap.html

private load(): Observable<boolean> {
    return this.accessControl.flatMap((res: any) => {
        if (res.accessGranted) {
            return this.dataService.getData(res.id);
        } else {
            return Observable.of(null);
        }
})

then subscribe to this observable sequence. this will chain the api calls. here is a good resource on flatMap https://coryrylan.com/blog/angular-multiple-http-requests-with-rxjs

like image 124
LLai Avatar answered Nov 23 '25 14:11

LLai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!