peter.cambal
peter.cambal

Reputation: 522

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

Upvotes: 1

Views: 763

Answers (2)

Fan Cheung
Fan Cheung

Reputation: 11380

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)

Upvotes: 1

gil
gil

Reputation: 2552

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)

Upvotes: 2

Related Questions