Skip to content

Instantly share code, notes, and snippets.

@Flyrell
Last active November 29, 2019 18:35
Show Gist options
  • Save Flyrell/85807656f0d6a5aa0d655213505a1dab to your computer and use it in GitHub Desktop.
Save Flyrell/85807656f0d6a5aa0d655213505a1dab to your computer and use it in GitHub Desktop.
RxJS: Simple If condition for Observables in TypeScript
// Simple if condition that stops Observable from continuing passed condition function returns false.
// There's also an option to run else callback if needed.
/*
* USAGE
*
* of(events).pipe(
* ifCondition(event => event.name.endsWith('anything'), () => console.log('Not the anything event'))
* )
*/
export function ifCondition<I>(condition: (...args) => boolean, elseCallback?: (I) => any) {
return switchMap<I, Observable<I | never>>(value => {
if (condition(value)) {
return of(value);
}
if (elseCallback) {
elseCallback(value);
}
return NEVER;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment