⚠️ This lesson is retired and might contain outdated information.

Prevent unnecessary requests in Angular 2 with distinctUntilChanged

Share this video with your friends

Social Share Links

Send Tweet
Published 8 years ago
Updated 2 months ago

In this video you'll learn how to use the distinctUntilChanged operator to prevent making unnecessary requests.

[00:00] Now that we debounced the user input, we are saving our API from tons of unnecessary traffic, but there's still room for improvement, and [inaudible] makes things really easy.

[00:10] When I type ANG and then rest my fingers, we see the request going out. Now, let's see what happens when I hit backspace to cut the G, and then put it right back in. What happens is that we make two subsequent requests to fetch items for the term ANG.

[00:28] Since we're already displaying the search results for exactly that character sequence, we could actually save the request. Thinking in terms of observable streams, what we need is an operator to filter out subsequent duplicate notifications.

[00:42] Let's import the distinctUntilChanged operator, which does exactly that. We can think of it as a filter operator that works over a buffer of the last two notifications to remove duplicates. We add it right after debounceTime operator.

[00:54] Let's turn to our browser again and do exactly what we did before. We type ANG, and we see the request goes out. Now, I hit backspace, remove the G, and put it right back in, and I do that a couple of times. We notice that it's not making any new requests. It's still making new requests as soon as the term changes, which is exactly what we want.

egghead
egghead
~ 4 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today