Docs

What's Observable?

👉 Codes: finish custom observables.

Untitled

Create observable

There are several ways to create an observable from rxjs package.

// home.component.ts
import { interval, Subscription } from 'rxjs';

export class ... implements OnInit, OnDestroy {
	private firstObsSub: Subscription;

	ngOnInit() {
		this.firstObsSub = interval( 1000 ) // every seconds, a new event will be emitted
			.subscribe( count => {
				console.log(count); // log to the console
			})
	}

	// we have to .unsubscribe() -> if not, we get more and more observables
	//   whenever we get back to home
	ngOnDestroy(): void {
//|						// ^return nothing
//^whenever we leave the component
		this.firstObsSub.unsubscribe(); // prevent memory leak
	}
}

All observables provided by Angular → no need to import from "rxjs" + no need to unsubscribe().

.subscribe()

customIntervalObs.subscribe(
	<function_for_next>, // performed when get an emit
	<function_for_error>, // performed when there is error
	<function_for_complete> // perform when finish getting emit
);

You rarely build your own observable → use the ones given by angular or somewhere else. Below are just for more understanding how to do so if you want!

.create()

Create manually interval(),