timeout inside a subscription rxjs

ぐ巨炮叔叔 提交于 2020-05-30 08:46:28

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!