Avoid Swallowing Values
Learn how to avoid swallowing values while writing functions for RxJS operator functions and how to handle time-based events with RxJS Observables.
We'll cover the following...
How to prevent value loss
When writing functions that are used by the RxJS operator functions, we need to be careful that we continue to return values and do not swallow them unexpectedly.
Consider the following code:
const emitOneTwo = of(1, 2); // create an Observable that emits 1 and 2const swallowedValues = emitOneTwo.pipe(map((value: number) => {console.log(`swallowing ${value}`); // log value but don't return it// not returning a value;}));swallowedValues.subscribe((value: void) => {console.log(`subscriber received value: ${value}`); // log the void value received});
-
We have an Observable named
emitOneTwoon line 1 that will emit the values1and2. -
We then
pipethese values into theswallowedValuesObservable on line 2. -
Note the
mapfunction on line 3 that we have provided here. All it is doing is logging a message to the console. It does not return a value. -
because the
mapfunction does not return a value, oursubscribefunction on line 8 must define the type of the incomingvalueparameter asvoid.
When we run the above code, we can see the side effects of not returning a value from a map function.
- Firstly, the
mapfunction will be called for each value that is emitted from theemitOneTwo