Do I need to unsubscribe when using switchMap statement in rxjs in Angular 2?

Angular 2 has some observables that you don't need to unsubscribe. For example, HTTP requests and activated Route.params.

Angular / RxJs When should I unsubscribe from Subscription

But what happens when I use a switchMap like activRoute.params and inside that switch I am accessing a service that returns an observable that should be unsubscribed when subscribing in the usual way.

Something like that:

this.activatedRoute.params
    .switchMap((params: Params) => this.userService.getUser(+params['id']))
    .subscribe((user: User) => this.user = user);

      

If I called this.userService with no switchMap and no Route.params enabled, I would have to abandon it.

// userService.getUser() takes in optional id?: number.
this.subscription = this.userService.getUser().subscribe(
    (user: User) => {
        this.user = user;
    }
 );

      

And then later ..

this.subscription.unsubscribe();

      

My question is, do I need to unsubscribe from activRoute.params if I use switchMap on it and call a service that needs to be unsubscribed otherwise?

+3


source to share


1 answer


If the source you are subscribing to always ends or errors, you don't need to unsubscribe.

However, if you create another observable from source using switchMap

, whether or not you need to unsubscribe depends on the observable returned in switchMap

. If the returned observation is not always complete or an error, then yes, you need to unsubscribe.

If source errors occur, the subscription will be automatically canceled:



const source = new Rx.Subject();
const composed = source.switchMap(() => Rx.Observable.interval(200));

composed.subscribe(value => console.log(value));
source.next(1);

setTimeout(() => {
  console.log("Erroring...");
  source.error(new Error("Boom!"));
}, 1000);
      

.as-console-wrapper { max-height: 100% !important; top: 0; }
      

<script src="https://unpkg.com/rxjs@5.4.1/bundles/Rx.min.js"></script>
      

Run code


However, if the source is complete, automatic unsubscribe will not take place:



const source = new Rx.Subject();
const composed = source.switchMap(() => Rx.Observable.interval(200));

composed.subscribe(value => console.log(value));
source.next(1);

setTimeout(() => {
  console.log("Completing...");
  source.complete();
}, 1000);
      

.as-console-wrapper { max-height: 100% !important; top: 0; }
      

<script src="https://unpkg.com/rxjs@5.4.1/bundles/Rx.min.js"></script>
      

Run code


+5


source







All Articles