Observable

import { Observable } from '@hullo/core'

In case this is your first contact with Observer pattern and Observables, be sure to check out Intro page.

Observable constructor can have either:

A simple producer function

import {
Producer,
Observer,
Observable
} from '@hullo/core';
const producer: Producer<any> =
(observer: Observer<any>) => { /* ... */ };
const subject = new Observable(producer);

A producer function returning another function called when cancel method on Subscription is called

import { Observable } from '@hullo/core';
const subject = new Observable<string>(
observer => {
const token = setTimeout(() => {
observer.next('surprise!');
}, 0);
return function onCancel () {
clearTimeout(token);
}
);
const sub = subject({ next: console.log });
sub.cancel()
// since this is called immediately,
// and calls clearTimeout synchronously,
// a message is never emitted by console.log

Async function producer (returned Promise is ignored)

import { Observable } from '@hullo/core';
const subject = new Observable<number>(
async observer => {
await observer.next(10);
await observer.next(9);
await observer.next(8);
// ...
}
);

Complex producer

An Observable constructor can also have a producer object with only subscribe method, receiving an observer, required.

Independently of if the producer is a function or an object, a cancellation can also be a function or an object with only cancel method required.

import { Observable, Observer } from '@hullo/core';
/*
all of this should create an observable
that emits a random number every 300ms
*/
const subject =
new Observable<number>(
{
time: 300,
timer: { token: null },
subscribe
}
);
function subscribe(
this: { time: number, timer: { token: any },
observer: Observer<number>
) {
this.timer.token = setInterval(
() => observer.next(Math.random()),
this.time
);
return {
timer: this.timer,
cancel
};
}
function cancel(
this: { timer: { token: any },
) {
clearInterval(this.timer.token);
}