Last active
December 3, 2021 11:30
-
-
Save dmorosinotto/f98370a39d9041358915b8a493cf3654 to your computer and use it in GitHub Desktop.
RxJS usefull custom operators: mapFilter + debug (LIVE SAMPLE https://stackblitz.com/edit/rxjs-74qvro?devtoolsheight=60)
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
import { map, filter, tap } from "rxjs/operators"; | |
import { Observable } from "rxjs"; | |
export function mapFilter<T,R>(fnTrasformSkipUndefined: (value: T)=>R) { | |
return function(source: Observable<T>): Observable<Exclude<R, undefined>> { | |
return source.pipe(map(fnTrasformSkipUndefined), filter(value => value !== undefined)) as Observable<Exclude<R,undefined>>; | |
} | |
} | |
//INSPIRED BY @netbasal ARTICLE https://netbasal.com/creating-custom-operators-in-rxjs-32f052d69457 | |
export function debug(tag: string) { | |
return tap({ | |
next(value) { | |
console.log(`[${tag}: Next]`, value) | |
}, | |
error(err) { | |
console.error(`[${tag}: Error]`, err) | |
}, | |
complete() { | |
console.warn(`[${tag}: Completed]`) | |
} | |
}) | |
} |
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
import { interval, take } from "rxjs"; | |
import { mapFilter, debug } from "./customOperators.ts"; | |
interval(100).pipe(take(11), | |
debug("before"), | |
mapFilter(n => { | |
if (!n) return null; //IT WILL KEEP null | |
if (n%5 == 0) return false; | |
else if (n%2) return n + " is odd"; | |
//IF n IS NOT multiple of 2 or 5 return undefined -> DONT EMIT | |
}), | |
debug("after") | |
).subscribe(res => console.info(typeof res)); //CORRECTLY INFER res: string|false|null | |
/* //PRINTOUT OR TRY LIVE ON https://stackblitz.com/edit/rxjs-74qvro?devtoolsheight=60 | |
[before: Next] 0 | |
[after: Next] null | |
object | |
[before: Next] 1 | |
[after: Next] 1 is odd | |
string | |
[before: Next] 2 | |
[before: Next] 3 | |
[after: Next] 3 is odd | |
string | |
[before: Next] 4 | |
[before: Next] 5 | |
[after: Next] false | |
boolean | |
[before: Next] 6 | |
[before: Next] 7 | |
[after: Next] 7 is odd | |
string | |
[before: Next] 8 | |
[before: Next] 9 | |
[after: Next] 9 is odd | |
string | |
[before: Next] 10 | |
[after: Next] false | |
boolean | |
[before: Completed] | |
[after: Completed] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment