need combination of map and filter operator (choose) #6066
Replies: 5 comments 3 replies
-
|
Beta Was this translation helpful? Give feedback.
-
Flatmap could do it - either map to empty or a sequence of 1 but not very intuitive and harder to use. |
Beta Was this translation helpful? Give feedback.
-
In F# they call it
|
Beta Was this translation helpful? Give feedback.
-
Yes and no... You can help TS, like this: test() {
let source: Observable<string | null>;
let result = source.pipe(
filter((i): i is string => i !== null),
map((i) => i.toUpperCase()) // now you no longer need the `!` anymore :slightly_smiling_face:
);
} Also, if you somehow have the guarantee that the source won't emit any empty strings, then in RxJS v7 you will be able to do this: test() {
let source: Observable<string | null>;
let result = source.pipe(
filter(Boolean),
map((i) => i.toUpperCase())
);
} |
Beta Was this translation helpful? Give feedback.
-
function isNotNull<T>(value: T): value is Exclude<T, null> {
return value !== null;
}
declare const a$: Observable<string | null>;
const b$: Observable<string> = a$.pipe(filter(isNotNull)); |
Beta Was this translation helpful? Give feedback.
-
Suppose you have a stream of X | null. How do you map every X to Y and exclude the nulls? Like this...
TypeScript isn't smart enough to know that after the filter, I'm just left with a stream of
string
and still thinks I have a stream ofstring | null
. So I have to use the!
operator to force the conversion which generates an eslint error. Annoying! Is there some workaround I don't know about?In F# there is a
choose
operator that is a combination of map and filter. If the mapping operation results inNone
(or undefined for javascript), it is filtered out and otherwise you get the mapped value. I'd love to see this kind of thing as a standard rxjs operator and am surprised it isn't here by default. Seems like a common need. For example, Firebase gives a stream of user identities where null represents a user who isn't logged on and I can't easily map the logged in users only. In F# I use it all the time when working with sequences.If I had this operator I could do this...
I'm not familiar with the rxjs operator types, but it would be something like this. If the projection results in
undefined
then it is filtered out.Beta Was this translation helpful? Give feedback.
All reactions