Skip to content

Instantly share code, notes, and snippets.

@harbirchahal
Last active October 16, 2022 15:11
Show Gist options
  • Save harbirchahal/765c82de185268884b9b9f62dc835584 to your computer and use it in GitHub Desktop.
Save harbirchahal/765c82de185268884b9b9f62dc835584 to your computer and use it in GitHub Desktop.
import { Injectable } from '@angular/core';
import { BehaviorSubject, Subscription, Observable } from 'rxjs';
import { interval } 'rxjs/operators';
@Injectable()
export class IntervalService {
private subject = new BehaviorSubject<number>(-1);
private subscription: Subscription;
readonly observable$ = this.subject.asObservable();
start() {
const countdown = this.limit();
this.subscription = Observable.interval(1000).subscribe(value => {
value = countdown - value;
if (value >= 0)
this.subject.next(value);
else
this.stop();
});
}
stop() {
if (this.subscription) {
this.subscription.unsubscribe();
this.subscription = undefined;
}
}
restart() {
this.stop();
this.start();
}
limit() {
return 120;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment