Skip to content

Instantly share code, notes, and snippets.

@xtianjohns
Created June 4, 2017 18:41
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 xtianjohns/f5634237a25de013d23527d72d1a74e3 to your computer and use it in GitHub Desktop.
Save xtianjohns/f5634237a25de013d23527d72d1a74e3 to your computer and use it in GitHub Desktop.
takeWhile for fun and for profit
import { Component, OnInit, OnDestroy } from '@angular/core';
import { MyService } from './MyService.ts';
import 'rxjs/add/operator/takeWhile';
@Component({
selector: 'my-rad-component',
})
export class MyComponent implements OnInit, OnDestroy {
/* A boolean for monitoring the destruction of the component. */
private isDestroyed: boolean = false;
/* Inject a service with an observable API. */
constructor(private myService: MyService) { }
ngOnInit() {
this.myService.getData() /* Fetch some data. */
.takeWhile( () => !this.isDestroyed ) /* Take events as long as we are not destroyed. */
.subscribe( data => {
// do something with your data, AKA: define your effects.
});
}
ngOnDestroy() {
this.isDestroyed = true; /* Update our state. */
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment