AngularDebutant
AngularDebutant

Reputation: 1576

timeout inside a subscription rxjs

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.

Upvotes: 1

Views: 3276

Answers (2)

Jonathan Stellwag
Jonathan Stellwag

Reputation: 4287

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:

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);
}

Upvotes: 2

martin
martin

Reputation: 96979

You can use tap and delay:

this.someFormGroup.controls['control1'].valueChanges
  .pipe(
    tap(val => {
      if (val) {
        doStuff();
      }
    }),
    delay(1000),
  )
  .subscribe(() => doOtherStuff());

Upvotes: 0

Related Questions