DEV Community

Blake Lamb
Blake Lamb

Posted on • Updated on

How To Use The 'Concat' RxJS Operator To Make Synchronous HTTP Calls

Overview

Sometimes it is necessary to be able to make HTTP calls in a synchronous order. This can be difficult to do, but with the RxJS operator 'Concat', it is much simpler.

Getting Into It

Open an Angular app to the component that needs to run the synchronous calls, or create a sandbox Angular app. Knowing what an observable is and how to create/use them is necessary to use Concat. If observables are a new concept, do some research about that first.

Open an Angular app to the component that needs to run the synchronous calls, or create a sandbox Angular app. Knowing what an observable is and how to create/use them is necessary to use Concat. If observables are a new concept, do some research about that first.

In the component that the synchronous calls need to be made create a array of the calls as observables, but don't subscribe to each observable. That should look something like the example below:

// app.component.ts

ngOnInit(): void {
  const calls = [
    this.fetchCharacter("1"),
    this.fetchCharacter("2"),
    this.postCharacter(),
    this.postCharacter(),
    this.postCharacter()
  ];

  concat(...calls).subscribe(
    res => console.log("next", res),
    err => console.log("error", err),
    () => console.log("complete")
  );
}

fetchCharacter(characterId: string): Observable<any> {
  return this.httpClient.get( "https://jsonplaceholder.typicode.com/todos/" + characterId );
}

postCharacter(): Observable<any> {
  return interval(3000).pipe(
    take(1),
    switchMap(() => {
      return this.httpClient.post("https://jsonplaceholder.typicode.com/todos", {} );
    })
  );
}
Enter fullscreen mode Exit fullscreen mode

As you can see, the 'calls' array is created with five observables created by calling the fetchCharacter() and postCharacter() methods. The post Character method waits each time it is called, so there is a clear time lag between each time the method is called.

Once the calls array is created with the observables, spread that array into the concat method. When the concat method is subscribed to, each observable in the array passed into it will be subscribed to and execute in order. In the example above, you can see the characters logged to the console at set intervals. Then once all the observables have been executed, the finished message that is passed into the concat method as the final argument is executed.

Wrap Up

This can be a very valuable RxJS operator to utilize. Often times having code execute asynchronously is preferred and can increase the speed of functions. But in instances where the code much be synchronous, concat is a great way to accomplish that.

For a live example of the above code, see this StackBlitz

Top comments (0)