This lesson is for PRO members.

Unlock this lesson NOW!
Already subscribed? sign in

Handling Clicks and Intervals Together with Merge

1:36 Angular 2 lesson by

Observable.merge allows you take two different source streams and use either one of them to make changes to the same state of your data. This lesson shows how you can use a stream of clicks and an interval stream and use either one to update the clock.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

Observable.merge allows you take two different source streams and use either one of them to make changes to the same state of your data. This lesson shows how you can use a stream of clicks and an interval stream and use either one to update the clock.

Avatar
Eric

Hi! I'm new to Rx.js and Typescript. Wondering if there's an easier way to import all dependencies? It seems like a bit of a hassle to have to add a new import statement every time we want to use a new method...

Avatar
Jesse

@Eric You could probably import the whole libraries and it would work, but be very difficult to sort out later what your not using. So import as you go is a better practice. There are some IDEs that support auto importing when you first reference something that has not yet been imported. https://blog.jetbrains.com/webstorm/2016/04/angular-2-workflow-in-webstorm/#ng2-imports

In reply to Eric

For my time machine I do want my observable interval always running. I do want it to update every second. But I also want the clicks to be able to update it. From other observable lessons we've learned that observable.merge is what we use when we want one stream or another stream to update the same thing.

We can say observable.merge, which can take these two observables. We'll say this click, because a subject is a type of observable, and we'll say observable.interval. Let me get rid of that semicolon, either one of these can go ahead and map to a new date. Then I can take my clock and assign it to that stream of merge.

What I'm going to do here just to show this off is change this to five seconds so that now when I refresh here, you see that I forgot to import merge. You'll forget to import these a lot, so just expect these to pop up every now and again. I'll say import/merge. Let's save again.

I'll refresh. Now you'll see this clock. Nothing happens, nothing happens, nothing happens, but after five seconds it'll show up. Now it's just sitting there, but I can click Update to make it update. Then after five seconds it automatically updates itself.

We have those two streams working for us. Whenever I click or whenever five seconds passes my clock will now update.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?