export class AppComponent {
title = 'app';
observable$;
ngOnInit() {
// create an observable
this.observable$ = Observable.create((observer) => {
observer.next(1);
observer.next(2);
observer.next(3);
observer.complete();
});
this.observable$.subscribe(
value => console.log(value),
err => {},
() => console.log('this is the end')
);
}
ngOnDestroy() {
// unsubscribe an observable, otherwise it'll keep on listening even if the component is destroyed
this.observable$.unsubscribe();
}
}
// Logs
// 1
// 2
// 3
// "this is the end"
/*
Calling next with a value will emit that value to the observer.
Calling complete means that Observable finished emitting and will not do anything else.
Calling error means that something went wrong - value passed to error method should provide details
on what exactly happened.
A well-formed Observable can emit as many values as it needs via next method, but complete and error methods
can be called only once and nothing else can be called thereafter. If you try to invoke next, complete or
error methods after created Observable already completed or ended with an error, these calls will be ignored
to preserve so called Observable Contract. Note that you are not required to call complete at any point
- it is perfectly fine to create an Observable that never ends, depending on your needs.
*/
const observable = Rx.Observable.create((observer) => {
observer.error('something went really wrong...');
});
observable.subscribe(
value => console.log(value), // will never be called
err => console.log(err),
() => console.log('complete') // will never be called
);
// Logs
// "something went really wrong..."