Skip to content

Instantly share code, notes, and snippets.

@yjaaidi
Created May 30, 2018 12:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yjaaidi/9baf3f077a24ac07e4d0569ae46db3cd to your computer and use it in GitHub Desktop.
Save yjaaidi/9baf3f077a24ac07e4d0569ae46db3cd to your computer and use it in GitHub Desktop.
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Subject, interval } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
@Component({
template: `
<div>{{ count }}</div>
<button (click)="startCounting()">Start Counting</button>
`
})
export class CounterComponent implements OnInit, OnDestroy {
count: number;
private _destroyed$ = new Subject();
ngOnInit() {
this.startCounting();
}
ngOnDestroy() {
this._destroyed$.next();
this._destroyed$.complete();
}
startCounting() {
interval(1000)
.pipe(takeUntil(this._destroyed$))
.subscribe(count => this.count = count);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment