Search code examples
angularrxjsrxjs6

How to skip subscribe result?


I have an stream changes$ that emits data:

interface Data {
  id: number,
  prop: string
}

This stream is switched by another that makes http request.

In the end I subscribe to response:

.subscribe((response =>apply() );

How dont call apply() method if before getting response from last request a new data were emitted to initial stream?

Because despite http request was sent the data is outdated, cause source stream changes$ emits a new data.


Solution

  • If I understand right the question, what you are looking for is something like this

    • the process starts with changes$ emitting a value of type Data
    • once a Data instance is emitted by change$ then an http request is fired, probably with that instance of Data as parameter but this is not relevant in this case
    • once the response of the http request is received, the apply function is executed, probably with the response received as parameter but again this is not relevant
    • BUT if, before having received the response from http, another instance of Data is emitted by change$, then the previous http request is cancelled and we just wait for the result of the second request before calling apply

    If this is all true, then the operator you are looking for is switchMap which does unsubscribe any previous subscription to its inner observable (i.e. it cancel any http request on fly in this case) and starts a new subscription any time it receives a new notification from the upstream Observable.

    The code would look like this

    change$.pipe(
       switchMap(data => fireHttpRequest(data)),
    ).subscribe(
       response => apply(response)
    )