Initial value!

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:

  • The output stream starts by emitting immediately this initial value.


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

  • ❚ fromEvent reacts to the ▬ toggle. It creates a sequence of toggle events over time, in reaction to each toggle status change (read Episode 1).
  • ❚ map projects each toggle events to ✔ true or ✘ false (read Episode 2).
  • ❚ subscribe adds ▬ setWifi as a listener of the stream. This listener accepts boolean values (✔ true or ✘ false) and turns the wifi on or off accordingly.

Watch Episode 3 ↗

It begins like this:

  • the application starts
  • after a few seconds, the toggle is turned off by the user
  • so, a first event ✘ false is emitted
  • as a result, the listener turns the wifi component off
  • and so on…

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 ✔ true event value:

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


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?

Cédric Soulas Follow Hire me

Freelance Developer Advocate. Motion graphics with code. JavaScript and Elm.

Subscribe to newsletter

Receive my latest news, tips and animations:

Learn Reactive Programming and stay up-to-date: