'Having RxJS observable active for certain time

I have a FormControl for which I want to have a 'statusChanges' observable that should be deactivated after 2 seconds or after receiving the first emit whichever is earlier.

The below example deactivates the observable after receiving the first emit. But, it will be active for long time when there is no statusChanges for the FormControl:

this.formControl
  .statusChanges.pipe(first())
  .subscribe(() => {
    // DO MY STUFF
  });


Solution 1:[1]

The RxJS operator timeout exists exactly for such scenarios. It'll emit an error if the source observable hasn't emitted for a give amount of time.

export const LIMIT = 2000;    // <-- time in ms

this.formControl.statusChanges.pipe(
  first(),
  timeout(LIMIT)
).subscribe(() => {
  // DO MY STUFF
});

Solution 2:[2]

this is my solution:

this.formControl
  .statusChanges
  .pipe(
    first(),
    takeUntil(this.destroy$),
  )
  .subscribe(() => {
    // DO MY STUFF
  });

timer(2000);
  .subscribe(() => {
     this.destroy$.next();
     this.destroy$.complete();
  });

Solution 3:[3]

Another solution it to merge a timer and take the first from whichever emits.

merge(
  this.formControl.statusChanges,
  timer(2000)
).pipe(
  first()
).subscribe(() => {
  // DO STUFF
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ruth
Solution 2 Hamid Taebi
Solution 3 Mrk Sef