I want to talk about something that bothers me. I see a lot of articles that talks about how to solve the multiple HTTP requests problem when using the async pipe. If you don’t know what I’m talking about, let me refresh your memory.

When working with the async pipe and Observable, you can get to a situation that you have multiple HTTP requests. For example:

You can see that we are firing three requests to the server. This is happening because our Observable is cold and every use of the async pipe creates new execution.

The current solution that people suggest:

Just use the share operator, which internally call to publish().refCount().

But then you have a situation of future subscriber like this:

<p *ngIf=”show”>{{ (person | async)?.userId }}</p>

Which in this case share does not help you and when you will show the element one more HTTP request will fire. So to solve this problem you need to use the publishReplay operator and call the connect method.

At this point, I am asking myself:

Why???? This is the right thing to do??

When you have a single event, just use promise.

In most of the cases, we just need to GET data from the server and display the data, and we are done.

Let’s fix the multiple HTTP requests problem with a promise:

Great! Now it does not matter when, how and why you always get the latest value without firing another HTTP request.

The second solution — don’t use the async pipe:

Conclusion:

Rx is the most powerful library that I know when it comes to asynchronous operations. But you don’t always need to use Observables. Promises are still here, and it’s OK to use them when you have a single event as we saw in this article.

That’s all!

☞ Please tap or click “︎❤” to help to promote this piece to others.