Handle Clicks and Intervals Together with Merge

John Lindquist
InstructorJohn Lindquist

Share this video with your friends

Send Tweet
Published 7 years ago
Updated 3 months ago

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.

[00:00] 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.

[00:21] 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.

[00:55] 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.

[01:13] 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.

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

Eric Bolikowski
Eric Bolikowski
~ 7 years ago

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...

~ 6 years ago

@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