Sharing Streams with Share

InstructorJohn Lindquist

Share this video with your friends

Send Tweet

A stream will run with each new subscription added to it. This lesson shows the benefits of using share so that the same stream can be shared across multiple subscriptions.

Chris
~ 8 years ago

Can we use do() instead of subscribe() to clear the text to simplify things?

Vincent De Snerck
~ 8 years ago

'Do' definitely seems like a better solution for the problem. Double subscribe also seems to go against what was said in an earlier video where the entire working of the stream should be defined at declaration.

However it is an example of how and why you could share a stream.

Jordan Frankfurt
~ 8 years ago

first try

ganqqwerty
~ 6 years ago

great course, thanks so much!

J. Matthew
~ 5 years ago

'Do' definitely seems like a better solution for the problem. Double subscribe also seems to go against what was said in an earlier video where the entire working of the stream should be defined at declaration.

I think you're referring to this video: https://egghead.io/lessons/rxjs-reactive-programming-why-choose-rxjs

However, I think the sense of it is a bit different than your interpretation. If I'm understanding it right, that video argues that the behavior of the dynamic values of the stream itself should be defined at declaration.

The author gives the example of a stream that just emits the value "3," and then incorrectly modifying it later to also emit 4. Or setting one value based on another value, but doing so in two different places. This is what one shouldn't do.

In the video on this page, on the other hand, subscribing to the stream in more than one location doesn't violate this principle, because the additional subscribe doesn't further modify the stream itself. Like the author says, it's a side-effect, just triggering another effect on the DOM whenever the stream emits.

It's true that input.value is modified in two places (though set to an empty string each time), and maybe that would still be frowned upon; I'm still wrapping my head around that side of things. But the input stream is emitting the input event, which isn't triggered by setting the input's value programmatically. So the stream isn't being affected. At least, I don't think so.

It's a good question about whether do() would work and be more appropriate. Consider though that the share() operator wouldn't be made available if there weren't valid uses for more than one subscribe().