LppEdd
LppEdd

Reputation: 21134

Typescript - modify array values on destructuring

Say I have this piece of code:

const [val$, err$] = partition(result => ...)(httpSource$)
const valid$ = val$.pipe(
    tap(() => ...),
    map(result => ...)
)
const error$ = err$.pipe(
    tap(() => ...),
    map(result => ...)
)

Can I avoid creating the val$ and err$ variables, by modifying the partition return value before assignment?

Upvotes: 1

Views: 597

Answers (1)

ggradnig
ggradnig

Reputation: 14179

There is usually no need to partition an Observable just for the error handling. Instead, we can use the throwError creation function to create an error notification. Error notifications are handled separately in your subscribe call (the second parameter of subscribe is a function that is called on error).

A typical example for custom error handling could look like this:

$httpSource.pipe(
    mergeMap(res => 
        res.error ? 
            throwError(res.error) : 
            of(res.value)
    ),
    tap(next => ..., err => ...)
).subscribe(
     next => ..., 
     err => ...
)

I'm using mergeMap, because throwError creates an inner Observable that must be merged in the outer Observable. Note, that both tap and subscribe take a second argument for the error handling function.

More about error notifications: The Observable Contract defines three types of notifications that can be passed along the chain. One of them is the error notification, that is defined as:

[the error notification] indicates that the Observable has terminated with a specified error condition and that it will be emitting no further items

Catching and rethrowing-errors: If an error notifcation comes along the Observable chain, we can gracefully catch that error and convert it to a different notification by using catchError:

$httpSource.pipe(
    catchError(err => throwError(new CustomError(err)))
).subscribe(
     next => ..., 
     err => ...
)

Upvotes: 2

Related Questions