What are pure and impure pipes?

998    Asked by MelvinForbis in Python , Asked on Dec 4, 2019
Answered by Melvin Forbis

A pure pipe is only called when Angular detects a change in the value or the parameters passed to a pipe. An impure pipe is called for every change detection cycle no matter whether the value or parameter(s) changes.

This is relevant for changes that are not detected by Angular

When we pass an array or object that got the content changed (but is still the same instance)

When the pipe injects a service to get access to other values, Angular doesn't recognize if they have changed.

In these cases, we probably still want the pipe to be executed.

We should be aware that impure pipes are prone to be inefficient. For example, when an array is passed into the pipe to filter, sort, ... then this work might be done every time change detection runs (which is quite often especially with the default ChangeDetectionStrategy setting) event though the array might not even have changed. Our pipe should try to recognize this and for example return cached results.

Angular provides AsyncPipe, which is state-full. In the following code, the pipe only calls the server when the request URL changes and it caches the server response. The code uses the Angular http client to retrieve data:



Your Answer

Interviews

Parent Categories