Unlike in part I of Angular pipes, async does not format existing data. It only waits for data to be received.
In the below example, we have our data bound to an observable, and then wait 1 second for data to be received after we click the button.
We know that data is received after 1 second, but we still need to subscribe to that data. When we use async, it subscribes automatically.
Advantages of using async include:
- Data can be an Observable rather than a Subscription.
- It unsubscribes automatically when the component is destroyed (no memory leaks).
- End up writing less code.
Pure vs Impure Pipes
By default, all pipes are pure. You can make them impure by creating a custom pipe and setting the property pure to false. Async is an example of an impure pipe. It is always checking for new input data.
The pure property tells Angular whether or not the value should be recomputed when its input changes.
When the pipe is pure, it does not check the input to see whether or not to update the transformed data.
Pure defaults to true for good reasons. Sometimes there is no need to keep recalculating on every change detection. On a large list of items, it could cause performance issues.
Angular defaults this behaviour to true and lets the developer decide whether or not impure is required.