Join egghead, unlock knowledge.

Want more egghead?


Unlock This Lesson
Become a member
to unlock all features

Level Up!



    Control Rx Subscriptions with Async Pipe and BehaviorSubjects

    John LindquistJohn Lindquist
    2 - 4

    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.



    Become a Member to view code

    You must be a Member to view code


    Become a Member
    and unlock code for this lesson




    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.

    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.

    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.

    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.

    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.

    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.