-
-
Save navix/b65eb82fc27efaa142d7d7e1bf78716f to your computer and use it in GitHub Desktop.
takeUntil for fun and for profit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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