问题
I have the following code
this.someFormGroup.controls['control1'].valueChanges.subscribe(val => {
if (val) {
doStuff();
}
setTimeout(() => doOtherStuff(), 1000);
});
I am wondering if there is another way to achieve this without the use of setTimeout, I was thinking about timer
from rxjs, but I am not sure how that could be incorporated here.
回答1:
You can use tap
and delay
:
this.someFormGroup.controls['control1'].valueChanges
.pipe(
tap(val => {
if (val) {
doStuff();
}
}),
delay(1000),
)
.subscribe(() => doOtherStuff());
回答2:
Altough the above solution works, pipe side effects are never the solution you want to go for. One of the big advantages at Rx is that you always know what happens, when and how. There are lot's of articles around why you should not use side effects in general:
- Coding style - Why is using side effects bad practice in JavaScript constructors?
- when should we use the rxjs tap operator.
Also keep in mind: It is always, really always possible to implement solutions without tap and most of the times it's pretty easy as you can see down.
private readonly valueChanges$: Observable<any> = this.someFormGroup.controls['control1'].valueChanges
private readonly delayedValuechanges$: Observable<any> = this.valueChanges$.pipe(
delay(1000)
)
constructor(private readonly someFormGroup: SomeFormGroup) {
this.valueChanges$.subscribe(this.doStuff);
this.delayedValueChanges$.subscribe(this.doOtherStuff);
}
来源:https://stackoverflow.com/questions/60216581/timeout-inside-a-subscription-rxjs