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
:
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.It begins like this:
✘ false
is emittedBut, 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?
Freelance Developer Advocate. Motion graphics with code. JavaScript and Elm. cedricsoulas.com
Receive my latest news, product updates and programming visualizations. You can unsubscribe at any time.