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
- The output stream starts by emitting immediately this initial value.
❚ fromEventreacts to the
▬ toggle. It creates a sequence of toggle events over time, in reaction to each toggle status change (read Episode 1).
❚ mapprojects each toggle events to
✘ off(read Episode 2).
▬ setWifias a listener of the stream. This listener accepts
✘ offevent value and turns the wifi on or off accordingly.
It begins like this:
- the application starts
- after a few seconds, the toggle is turned off by the user
- so, a first event
✘ offis 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
✔ on event value:
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?