'Custom observable pipe function

I have a pipe function on my observable where i change value of response to empty array if result is null, or undefined.

obs.pipe(
        map(res => {
          // pipe and map function to return empty array if resource did not return result
          return res ?? [];
        })
      );

i am using this functionality on multiple places and I am wondering if I can create some handler so I would not need to reuse this code.

My expectations:

this.loadCountries().pipe(defaultEmptyArrayPipe)

Thank you



Solution 1:[1]

you can achieve it by wrapping it with function which receives observable and returns an observable for example:

function defaultEmptyArrayPipe <T>(source$: Observable<T>): Observable<T> {
  return source$.pipe(
        map(res => {
          return res ?? [];
        })
      )
}

then call it as u wanted to:

this.loadCountries().pipe(defaultEmptyArrayPipe)

Solution 2:[2]

You can just wrap it with pipe and save it for reuse

    const defaultEmptyArrayPipe = pipe(map(res => {
      // pipe and map function to return empty array if resource did not return result
      return res ?? [];
    }))
   this.loadCountries().pipe(defaultEmptyArrayPipe)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 gil
Solution 2 Fan Cheung