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
emitOneTwo
on line 1 that will emit the values1
and2
. -
We then
pipe
these values into theswallowedValues
Observable on line 2. -
Note the
map
function 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
map
function does not return a value, oursubscribe
function on line 8 must define the type of the incomingvalue
parameter asvoid
.
When we run the above code, we can see the side effects of not returning a value from a map function.
- Firstly, the
map
function will be called for each value that is emitted from theemitOneTwo