Last active
November 29, 2019 18:35
-
-
Save Flyrell/85807656f0d6a5aa0d655213505a1dab to your computer and use it in GitHub Desktop.
RxJS: Simple If condition for Observables in TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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