Cédric Soulas
Motion graphics about programming

 

Episode 11 - Initial value! Monday, 27 Nov.

The first event emitted by a stream may happen some time after the stream has started (note: I’ll give more details on “how to start a stream” in a future episode).

In many cases, we have to wait for user clicks, for data to load, for an answer to arrive, etc. But, at the same time, we often want to compute or display initial data immediately when the request or the application starts.

Here is a new card: ❚ startWith. It looks like this:

Set an initial value on ❚ startWith, such as 0:

Example

In the Episode 3 we created a chain of 3 cards. Here is a small excerpt from this episode (or read the full episode):


Watch Episode 3 ↗

It begins like this:

But, from the pure perspective of the event stream, it’s not clear what is the status of the wifi component before the first interaction on the toggle. Is the wifi on by default? off? maybe in an undefined/buggy state?

I would like the chain of cards to be responsible for setting the initial state of the wifi component. To do so, I can add a fourth card to start with an initial ✔ on event value:

❚ fromEvent(toggle)
❚ map(isChecked)
❚ startWith(✔)
❚ subscribe(setWifi)

Conclusion

So, next time you want to display components with initial data, think “reactive” like you did for the rest of your app’s life cycle. Instead of using this separated and imperative function to set initial values, couldn’t you use ❚ startWith on this stream you already rely on?

Animated cards to learn Reactive Programming

Focus on one new concept every week with a 20 seconds gif

Occasional updates, plus:
Cédric Soulas
Motion graphics about programming