Observables often need to be stopped before they are completed. This lesson shows how to use
takeUntil to stop a running timer. Then we use the starting stream and the stopping stream together to create a simple stopwatch.
There's a few different approaches depending on the exact behavior you want. Here's one implementation:
For those of you looking for docs or info about switchMap and switchMapTo, it looks like these were added in version 5.0, they were previously known as flatMapLatest -> https://github.com/ReactiveX/rxjs/blob/master/MIGRATION.md
takeUntil will stop the stream it's attached to, so if you want to complete the
start$ stream, you would need to move the
start$ .switchMapTo(interval$) .takeUntil(stop$) .subscribe( x=> console.log(x), err => console.log(err), ()=> console.log('complete') );
Just be aware you'll no longer be able to click the start button, because the
start$ is completed.
Yep, when I started this video, my idea was to simply chain a takeUntil(stop$) on top of what we already had, something like this:
start$ .switchMapTo(interval$) .takeUntil(stop$) .subscribe(x => console.log(x));
So I didn't understand when you did something different. It was when I tried it myself that I realized that the code above will take
start$ until stop$, so it only worked once. On this case it's really just the
interval$ that we want to takeUntil(stop$).
Really enjoying this @John!