...

/

Avoid Swallowing Values

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.

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:

Press + to interact
const emitOneTwo = of(1, 2); // create an Observable that emits 1 and 2
const 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 values 1 and 2.

  • We then pipe these values into the swallowedValues 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, our subscribe function on line 8 must define the type of the incoming value parameter as void.

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 the emitOneTwo
...