Skip to content

Instantly share code, notes, and snippets.

@navix
Last active December 19, 2018 13:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save navix/aa4c7eecd84430613174bc976a9b92b5 to your computer and use it in GitHub Desktop.
Save navix/aa4c7eecd84430613174bc976a9b92b5 to your computer and use it in GitHub Desktop.

RxJS: finalCheck operator

Operator that will be runned on stream completition and throw error if callback return something.

Reason: finalize operator cannot pass error to a stream.

const finalCheck = (checkFn: () => any) => <T>(source: Observable<T>) =>
  new Observable<T>(observer => {
    return source.subscribe({
      next(x) {
        observer.next(x);
      },
      error(err) { observer.error(err); },
      complete() { 
        const err = checkFn();
        if (err) {
          observer.error(err);
        }
        observer.complete();
      }
    })
  });

Usage:

...pipe(
  ...
  finalCheck(() => {
    if (isError) {
      return 'Error message';
    }
  }),
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment