IObservable
Types
- IObservable
- IUnsubscribe
interface IObservable<GValue> {
(emit: IObserver<GValue>): IUnsubscribe;
}
interface IUnsubscribe {
(): void;
}
Definition
An Observable is a lazy push source able to emit multiple values.
It is simply a function accepting one argument (an Observer), and returning an unsubscribe function.
It's lazy, because the Observable emits values when subscribed, and stops when unsubscribed.
This is equivalent to the RxJS Observable or somehow an EventListener.
info
A best practice consist of post-fixing your Observables with $
.
It's a convenient way to distinguish them from the more classic variables.
Example: const value$ = of(1, 2, 3)
Example
Observable which emits 'void' every 500ms when subscribed
const subscribe: IObservable<void> = (emit: IObserver<void>): IUnsubscribe => {
const timer: any = setInterval(() => emit(), 500);
return (): void => {
clearInterval(timer);
};
};
const unsubscribe = subscribe(() => {
console.log('tick');
});
setTimeout(unsubscribe, 2100);
Output:
tick
tick
tick
tick
RxJS equivalent
new Observable<void>((subscriber) => {
const timer: any = setInterval(() => subscriber.next(), 500);
return (): void => {
clearInterval(timer);
};
});