RxJS Mastery – #58 startWith

The RxJS startWith operator allows sneaking in some fixed values before the actual emission of other values starts.

RxJS startWith to inform about loading

One common use case for startWith is informing the user about loading. As soon as the subscription to the source happens a first fixed value that is passed to startWith is emitted.

const source$ = cold('---r|', { r: 'response'});
const result$ = source$.pipe(startWith('loading...'));

expectObservable(result$).toBe(
    'l--r|',
    { l: 'loading...', r: 'response' }
);

RxJS startWith lets you define a default value

Similar to the loading indicator, startWith could be used to have some default value in the beginning. This might come in handy, e.g., for a form validation that first should be false as long as the validation was not successfully done. In the below example, we would like to validate the email address through an external service. As long as the validation result is not back yet, we would like to show it as not valid:

const verifyEmail$ = cold('---r|', { r: true});
const isValid$ = verifyEmail$.pipe(startWith(false));

expectObservable(isValid$).toBe(
    'd--v|',
    { d: false, v: true }
);

Exercise for the RxJS startWith operator 💪

Your task is to produce an interval sequence that makes the below marble diagram work:

expectObservable(result$).toBe(
    '(ab)c---d---(e|)',
    { a: -2, b: -1, c: 0, d: 1, e: 2 }
);

This post is part of the RxJS mastery series. As always the code examples can be found on GitHub.