How to "break" out of current pipe? #7316
-
What is the most idiomatic way to do this const source$ = new Subject<string | number>()
source$.pipe(
break((x: string | number): x is string => typeof x === "string"),
map(x => x + 1), // x should be inferred as of `number` type.
map(x => x * 2)
).subscribe((x) => console.log(x));
source$.next("this should bypass") // prints "this should bypass"
source$.next(10) // prints 22 I don't want to introduce any "nesting" of operators as I would if I use |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
You really can't.... source$.pipe(
map(x => x + 1),
map(x => x * 2)
)
source$.pipe(
map(x => x + 1)
).pipe(
map(x => x * 2)
)
const tmp$ = source$.pipe(
map(x => x + 1)
)
tmp$.pipe(
map(x => x * 2)
) How can you tell an operator that the value should be skipped over the next few operators? Those operators are just functions that take in an observable and return a new one. You have to imagine each observable as a standalone entity. You could just: const isString = (x: string | number): x is string => typeof x === "string";
const isNumber = (x: string | number): x is number => typeof x === "number";
merge(
source$.pipe(filter(isString)),
source$.pipe(
filter(isNumber),
map(x => x + 1),
map(x => x * 2)
)
) And if you don't like nesting, then break it down into smaller observables: const isString = (x: string | number): x is string => typeof x === "string";
const isNumber = (x: string | number): x is number => typeof x === "number";
const stringSource$ = source$.pipe(filter(isString));
const numberSource$ = source$.pipe(
filter(isNumber),
map(x => x + 1),
map(x => x * 2)
);
merge(stringSource$, numberSource$)
.subscribe(x => console.log(x)); Anything else you would need to write a custom |
Beta Was this translation helpful? Give feedback.
-
Thanks for that catch, I didn't see the part about the not wanting to nest stuff. There is a roundabout way to avoid callback hell, if it's that important: const source$ = new Subject<string | number>();
source$.pipe(
mergeMap((x: string | number) => {
if (typeof x === 'string') {
return throwError(x); // Throw an error to be caught later
}
return of(x);
}),
map(x => x + 1),
map(x => x * 2),
catchError((x: string) => of(x))
).subscribe(
x => console.log(x)
);
source$.next("this should bypass"); // prints "this should bypass"
source$.next(10); // prints 22 |
Beta Was this translation helpful? Give feedback.
You really can't....
pipe
is just taking one observable and passing it to the next operator. So these three ways are equivalent:How can you tell an operator that the value should be skipped over the next few operators? Those operators are just functions that take in an observable and return a new one.
You have to imagine each observable as a standalone entity. You could just: