Operators
Operators are simply functions. There are two kinds of operators:
Pipeable operators
- A Pipeable Operator is a function that takes an Observable as its input and returns another Observable.
- It is a pure operation: the previous Observable stays unmodified.
- Pipeable Operators are the kind that can be piped to Observables using the syntax
observableInstance.pipe(operator())
. - These include,
filter(...)
, andmergeMap(...)
. When called, they do not change the existing Observable instance. - Instead, they return a new Observable, whose subscription logic is based on the first Observable.
- A Pipeable Operator is essentially a pure function that takes one Observable as input and generates another Observable as output.
- Subscribing to the output Observable will also subscribe to the input Observable
Creation operators
- Creation Operators are the other kind of operator, which can be called as standalone functions to create a new Observable.
- For example: of(1, 2, 3) creates an observable that will emit 1, 2, and 3, one right after another.
Using pipeable operators
export class AppComponent implements OnInit, OnDestroy {
// `Observable` type which emits `number` data streams
observable: Observable<number>;
// subscription variable to hold observable subscription
// this is needed to dispose/destroy subscription whenever we need
subscription: Subscription;
ngOnInit(): void {
...
this.subscription = this.observable.pipe(
map(v => v * 2),
filter(v => v < 100)
).subscribe({
next(val) {
console.log(`next val is ${val}`);
},
error(err) {
console.log(`something went wrong: ${err}`);
},
complete() {
console.log('completed');
}
});
}
ngOnDestroy(): void {
this.subscription.unsubscribe();
}
}