Anna
Anna

Reputation: 149

Wait until HTTP call will end before sending a new http call from multiple observables - Angular

I have multiple observables that are basically listen to form-fields changes and each time the field value is changing, it's calling the API

My problem is that I've to wait until the ongoing api call is ended and only then perform another call.

The current implementation looks like this :

obs1$.pipe(
(tap(val) => callApi())
)

obs2$.pipe(
(tap(val) => callApi())
)

obs3$.pipe(
(tap(val) => callApi())
)

callApi() {
  this.http.post(url, someValue) <=== wait until this end
}

I've tried so many things but I just can't get it to work, any help would be appreciated

Upvotes: 0

Views: 1430

Answers (2)

Steve Holgado
Steve Holgado

Reputation: 12071

If you are looking to have only one API call in progress at a time, then I think you can solve your problem with the following:

merge(obs1$, obs2$, obs3$)
  .pipe(
    exhaustMap(() => callApi()),
  )
  .subscribe(val => console.log(val))

First merge your source observables into a single stream.

Then exhaustMap will ignore further values from your merged source observable until the observable returned from callApi() completes.

Upvotes: 0

Nichola
Nichola

Reputation: 532

you need a combination of combineLatest and concatMap

combineLatest([obs1$, obs2$, obs3#])
    .pipe(
        concatMap(([v1,v2,v3]) => callApi())

Upvotes: 1

Related Questions