Ben Cameron
Ben Cameron

Reputation: 4433

RxJs 6 chaining multiple subscriptions

I have an Angular 6 app. I'm upgrading rxjs to 6.

In the previous version of the app I had to make a call like this...

I call an observable Do something with its result Then call another observable using the value from the last Do something with its result

Do do this used concatmap. The code looked like this...

this.service1.getData().concatMap(d1 => {
            this.d1Local = d1;
            return this.service2.getData(d1);
        }).subscribe(
            this.d2Local = d2,
            error => errorFunction);

I'm trying to rewrite this using rxjs6 and the pipe keyword and without concatmap.

I currently have...

this._LocationService.getLocation()
    .pipe(           
        map(location => {
            console.log(1);
            this.location = location;
            return this._GeoCoderService.getAddress(location)
                .pipe
                (map(address => {
                this.address = "You are near " + address;
                    this.showSpinner = false;
                }
                ))
            }
        )   
);

I am never seeing '1' being logged to the console. Any ideas how I should be doing this?


UPDATE:

I know have the below code. I think its almost right how ever I am not seeing the last condole.log print 1....

this._LocationService.getLocation()
    .pipe(map((location: ILocation) => {
        this.location = location;
        return this._GeoCoderService.getAddress(location);
    })
        , catchError(error => { this.showSpinner = false; return throwError('Something went wrong!') })
    ).subscribe(
        tap((address: string) => { console.log(1) })
    );

What am I missing?

Upvotes: 1

Views: 5849

Answers (2)

kvetis
kvetis

Reputation: 7351

I wouldn't get rid of the concatMap operator. It is best suited for the job. To make things cleaner, I wouldn't store away the data inside the map operator either. For side-effects, tap is the best option for readable code.

this.service1.getData().pipe(
        tap(d1 => this.d1Local = d1),
        concatMap(d1 => this.service2.getData(d1),
    ).subscribe(
        d2 => this.d2Local = d2,
        error => errorFunction);

Upvotes: 4

dsych
dsych

Reputation: 762

After pipe() you should .subscribe() (observables are lazy and if you just do pipe() it does not trigger but subscribe does)

Upvotes: 2

Related Questions