1

I want to use switchMap in my subscriptions array, I want to call invokeRequest method which triggers http requests, basically I want to cancel subscription if same http call is triggered, can anyone please help.

private subscriptions: Subscription[] = [];
this.subscriptions.push(trigger.pipe(skip(1)).subscribe((e) =>
 this.invokeRequest(callConfig, e))
);

1 Answer 1

1

You can use switchMap in the pipe like below:

private subscriptions: Subscription[] = [];

this.subscriptions.push(
  trigger.pipe(
    skip(1),
    switchMap((e) => this.invokeRequest(callConfig, e))
  ).subscribe(resp => {
    // do something with the `invokeRequest` response
  })
);

This brings two main benefits:

  1. As you pointed out, when trigger emits a new value, the previous invokeRequest is cancelled (if it's still pending) and a new one is started.
  2. When you unsubscribe() your subscriptions (e.g when the component is destroyed), if there is some request pending, it's cancelled too. The way it was before (being called within the trigger.subscribe() callback) it would not cancel the request.
Sign up to request clarification or add additional context in comments.

1 Comment

Agreed! I'd also mark the better practice for Subscription: private subscriptions: Subscription = new Subscription(); and then just use this.subscriptions.add(... in the same way. It allows you only one time unsubscribe for all of your subscriptions in OnDestroy hook.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.