I just ran into the following issue
function doMagic(foo: boolean) {
return iif(
() => foo,
this.dialog.open(MyComponent).afterClosed(),
of(true)
).pipe( .... );
}
So, if foo === true
I want to open the dialog, if false, I don't and true
is emitted.
Now, the problem with this code is, that no matter what foo
is, the dialog will always open. Should I replace iif
with an if/else, something like this
function doMagic(foo: boolean) {
let stream = of(true);
if (foo) {
stream = this.dialog.....
}
stream.pipe(...);
}
or is there a way I can fix my initial code, such that, for example, the open
function behaves more as a stream.
CodePudding user response:
Using iif introduces unnecessary complication. The only point of using it is when you need to delay the execution of the condition until the moment of subscription. Your example doesn't need that and even if it did, using defer with a condition inside of it will be cleaner and more flexible. In fact, if you check the source, you'll see that iif just wraps defer. IMO, just avoid the iif operator entirely.
Your second example is fine, and you could make things a bit more concise with the conditional ternary operator.
doMagic(foo: boolean) {
const stream$ = (foo) ? this.dialog.open(MyComponent).afterClosed() : of(true);
return stream$.pipe(/* .... */);
}
Here's an example using defer where foo is some class variable. When somebody subscribes to the stream, the value of foo is checked then.
doMagic() {
return defer(() => (this.foo) ? this.dialog.open(MyComponent).afterClosed() : of(true))
.pipe(/* .... */);
}