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

Control Rx Subscriptions with Async Pipe and BehaviorSubjects

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 8 years ago
Updated 8 months ago

Each time you use the Async Pipe, you create a new subscription to the stream in the template. This can cause undesired behavior especially when network requests are involved. This lesson shows how to use a BehaviorSubject to observe the http stream so that only one request is made even though we still have two Async pipes in the template.

[00:00] You'll notice in the network tab that it makes a request to one twice, one being Luke Skywalker. The reason that happens is that this asynch pipe is essentially subscribing to this stream each time it's declared in the template. There's one subscription and two subscriptions, meaning that this stream is invoked twice. It makes this HTTP get request twice.

[00:25] What we can do to make the request happen only once is kind of flip what's going on meaning that instead of this contact being the stream itself, we can have the contact be what's called a behavior subject. We'll make sure to import this. Always remember to slash import it or else you'll import all of RXJS.

[00:46] Now this behavior subject is going to take the exact same thing that we passed in with start because a behavior subject starts with a value. It's essentially the same thing as saying start with down there. It's just that now it's declared at the beginning. Instead of start with, we're going to subscribe manually to the stream.

[01:10] The observer of this stream is going to be contact. Now you can read this as contact should start with a value name of loading and an image of nothing. Then we have a stream which is being observed by our contact so that each time this stream passes in new values, our contact will receive those values and load them.

[01:33] This will behave the exact same way except this time when we check the network tab, you'll see it only made one request this time. That's because we only have one subscription to the stream with HTTP get in it.

[01:46] We do have two subscriptions to this contact here and here because a behavior subject is still an observable but it's not going to make two requests because now it's just observing what comes from the stream instead of basically invoking it twice. Because now we have one subscription to the stream with HTTP calling it being observed by something with two subscriptions on it.

ganqqwerty
ganqqwerty
~ 7 years ago

Is there a material on how to organize my app when I have a lot of aspects of my state stored in the URL? For example, I have an search app, where I want my filters and search query to be in the URL, so that the user can easily share it.

Markdown supported.
Become a member to join the discussionEnroll Today