2

written code in angualr component to get the data from service every 10 sec on ngonit ,now I wanted to stop the interval running for every 10 sec post the certain time like 5 min or when data is collected.

Component code.

Getrecords() {
  Interval(10000).pipe(
    startWith(0),
    switchMap(() => this.getservice.getdata())
  ).subscribe(data => {
    this.code = data
  });
} 
Manish Balodia
  • 1,863
  • 2
  • 23
  • 37
vijay munnangi
  • 43
  • 1
  • 4
  • 13

3 Answers3

1

In my opinion rxjs timer would better suit this scenario like so:

const source = timer(0,10000);
source
.pipe(take(6*5),//take till 5 mins i.e. 30 times
takeWhile(()=>a==b))//your condition
.subscribe()
User3250
  • 2,961
  • 5
  • 29
  • 61
1

you need to unsubscribe from the observable.

private intervalSub: Subscription;

Getrecords() {
  this.intervalSub = Interval(10000).pipe(
    startWith(0),
    switchMap(() => this.getservice.getdata())
  ).subscribe(data => { this.code = data });
}

cancelInterval() {
  if (this.intervalSub)
    this.intervalSub.unsubscribe();
}

you may call this cancel function manually after a certain point, or in the on destroy hook (make sure component implements OnDestroy):

ngOnDestroy() {
  this.cancelInterval();
}

there are other ways of canceling an observable, such as adding in an operator that will complete it, such as take(20) if you only wanted 20 observations, or you could use the async pipe to let angular handle it automatically, but this is one surefire method.

bryan60
  • 28,215
  • 4
  • 48
  • 65
0

Extending the User3250 answer with switchMap

const source = timer(0,10000);
    source
    .pipe(take(6*5),//take till 5 mins i.e. 30 times
    switchMap(()=>this.service))
    .subscribe()
vijay munnangi
  • 43
  • 1
  • 4
  • 13