Search code examples
javascriptrxjsreactive-streams

How can I know if Observable has finalized with error or without error?


I need to execute some code when Observable is completed depending on whether has finalized with error or without. I have this code:

const obs = getMyObservable().pipe(finalize(() => {
    //here
}));

As you see, I'm using finalize operator, but I can't know if has finalized with or without error. Is there some kind of doOnComplete or doOnError operators in rxjs?


Solution

  • According to https://www.learnrxjs.io/

    With the latest RXJS you can use this 3 operators

    const obs = getMyObservable().pipe(                                       // Let's assume 'obs' returns an array
        tap(() => console.log('Action performed before any other')),
        catchError(() => { console.error('Error emitted'); return of([]); }), // We return [] instead
        finalize(() => console.log('Action to be executed always'))           // Either Error or Success
    );
    obs.subscribe(data => console.log(data));  // After everything, we log the output.
    

    Hope it helps

    EDIT based on JoniJnm comment

    To be More specific, there are, 3 main Pipes:

    1. Pipes that does alter the result before subscription.
    2. Pipes that does not alter the result before subscription.
    3. Special Pipes.

    Tap for example is from the second type, it can takes the input from the observable or previous pipes and do anything with it but cannot change the result of the pipe for the next step.

    Map is similar but it belongs to the first type of Pipe, it takes an input and has to return an output that can be used in the next pipe or final subscription.

    Finalize is a special pipe which does the same as Tap but after subscription. It is good for example to log final results or to cancel subscription after it completes.

    CatchError is a pipe which alters the result but it is only called if the previous step has thrown an error. This is used to avoid unhandled error and you should return an observable "default" instead of the failed observable (so we handle the error and the app does not break).

    You can guess when your observable had an Error if catchError has been launched and handle it straight away before it reach the subscription.

    If this pipe is not launched, the result is considered without error.