Hullo JS
Search…
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

1
import {
2
Producer,
3
Observer,
4
Observable
5
} from '@hullo/core';
6
​
7
const producer: Producer<any> =
8
(observer: Observer<any>) => { /* ... */ };
9
10
const subject = new Observable(producer);
Copied!

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

1
import { Observable } from '@hullo/core';
2
​
3
const subject = new Observable<string>(
4
observer => {
5
const token = setTimeout(() => {
6
observer.next('surprise!');
7
}, 0);
8
9
return function onCancel () {
10
clearTimeout(token);
11
}
12
);
13
​
14
const sub = subject({ next: console.log });
15
​
16
sub.cancel()
17
// since this is called immediately,
18
// and calls clearTimeout synchronously,
19
// a message is never emitted by console.log
Copied!

Async function producer (returned Promise is ignored)

1
import { Observable } from '@hullo/core';
2
​
3
const subject = new Observable<number>(
4
async observer => {
5
await observer.next(10);
6
await observer.next(9);
7
await observer.next(8);
8
// ...
9
}
10
);
Copied!

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.
1
import { Observable, Observer } from '@hullo/core';
2
​
3
/*
4
all of this should create an observable
5
that emits a random number every 300ms
6
*/
7
const subject =
8
new Observable<number>(
9
{
10
time: 300,
11
timer: { token: null },
12
subscribe
13
}
14
);
15
​
16
function subscribe(
17
this: { time: number, timer: { token: any },
18
observer: Observer<number>
19
) {
20
this.timer.token = setInterval(
21
() => observer.next(Math.random()),
22
this.time
23
);
24
25
return {
26
timer: this.timer,
27
cancel
28
};
29
}
30
​
31
function cancel(
32
this: { timer: { token: any },
33
) {
34
clearInterval(this.timer.token);
35
}
Copied!
Last modified 2yr ago