Some Tips for Working with Angular - From a Frontend Developer - Part 4.
Let's continue our journey on Angular.
As always, let me know in the comments if you find this interesting to read or if there's anything I can improve. I'd love to hear your feedback!
Note: These tips require prior knowledge and experience with Angular. I will not dive deep into RxJS or other fundamental concepts.
Asynchronous streams for an input array
Let's say you have an array of values and you want to perform an asynchronous action for each item. How can you achieve this using Observables?
In this case, the concatMap operator is the perfect choice. It allows you to process each item sequentially, waiting for the previous asynchronous operation to complete before moving on to the next one.
Here's how you can implement it:
const numbers = [1, 2, 3];
const test$ = from(numbers).pipe(
concatMap((number) => {
return of(null).pipe(
tap(() => console.log(number)),
delay(2000)
)
}),
)
With this code, when the source created by the from operator emits values, each emission will wait until the asynchronous operation inside concatMap completes before the next value is processed.
As a result, using the code above, the console.log statement will be executed after 2 seconds for each value, and the final result will be:
But we’re not done yet. What if you need to execute another synchronous action after that?
For example, suppose there is another tap operator placed after the previous one, like this:
const test$ = from(numbers).pipe(
concatMap((number) => {
return of(null).pipe(
tap(() => console.log(number)),
delay(2000)
)
}),
tap(() => console.log("This go here!")),
)
In this scenario, the "This goes here!" log statement will be executed after the function inside concatMap completes. As a result, the log function will run three times, once for each emitted value. Here is the output:
So, in this case, we need to use the last operator to ensure that the function is executed only after all values have been processed.
const test$ = from(numbers).pipe(
concatMap((number) => {
return of(null).pipe(
tap(() => console.log(number)),
delay(2000)
)
}),
last(),
tap(() => console.log("This go here!")),
)
With this implementation, the "This goes here!" log will be executed only once, after all the number logs have been completed.
Now, our stream is working exactly as intended. concatMap is really beneficial if you use it properly.
And that's all for blog #4 about the Angular tips! I hope you found these tips helpful. See you in my next blog!



Top comments (0)