This lesson is for PRO members.

Unlock this lesson NOW!
Already subscribed? sign in

Displaying Initial Data with StartWith

1:06 RxJS lesson by

You often need to render out data before you stream begins from a click or another user interaction. This lessons shows how to use startWith to set the initial output before you trigger your stream.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

You often need to render out data before you stream begins from a click or another user interaction. This lessons shows how to use startWith to set the initial output before you trigger your stream.

Avatar
Noah Rawlins

In my typescript compiler it complains that I am passing an object, {count: 0} to startsWith() for an interval observable that emits numbers.

I can explicitly type the interval$ as Observable to get around this, but that seems wrong.

Is there someway to put in the signature of scan that it converts this Observable to Observable<{count: number}> so the startsWith({count: 0}) doesn't generate an error?

This is with typescript 1.8.10 and rxjs 5.0.0 beta 7

You'll notice that once the page starts we have to click start for anything to come down in the console. You can imagine if we were rendering the timer somewhere in the dom, you probably want zero to show. You'd want this to fire one time to push a zero in there instead of waiting for that start to happen.

What we can do is instead of initializing scan with that second argument, we'll cut that out. We'll drop it up here as a constant called data. Then we'll use the StartWith operator.

Now when I hit save, you can see we start with an object that has a count of zero. Then, when I click start, we go one, two...I'll stop, and then start. Three, four.

That's because StartWith is going to set the initial value of scan, the initial accumulator, and then go ahead and push through to subscribe. In any stream you can send that initial value through and have it hit the subscribe block without having to trigger any other way of starting it.

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