Skip to content

Instantly share code, notes, and snippets.

@xtianjohns
Last active June 14, 2017 11:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save xtianjohns/1ce69be275fb8c395959d249bd02d1e2 to your computer and use it in GitHub Desktop.
Save xtianjohns/1ce69be275fb8c395959d249bd02d1e2 to your computer and use it in GitHub Desktop.
takeUntil for fun and for profit
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { MyService } from './MyService.ts';
import 'rxjs/add/operator/takeUntil';
@Component({
selector: 'my-rad-component',
})
export class MyComponent implements OnInit, OnDestroy {
/* A subject for monitoring the destruction of the component. */
private destroyed$: Subject<{}> = new Subject();
/* Inject a service with an observable API. */
constructor(private myService: MyService) { }
ngOnInit() {
this.myService.getData() /* Fetch some data. */
.takeUntil( this.destroyed$ ) /* Unsubscribe from the stream upon destruction. */
.subscribe( data => {
// do something with your data, AKA: define your effects.
});
}
ngOnDestroy() {
this.destroyed$.next(); /* Emit a notification on the subject. */
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment