-
Notifications
You must be signed in to change notification settings - Fork 1
/
observable-decorators.js
73 lines (63 loc) · 1.73 KB
/
observable-decorators.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/from';
import 'rxjs/add/operator/startWith';
const defaultConfig = {
toObservable: stream => stream,
fromObservable: Observable.from
};
export function observableFromConfig({ toObservable, fromObservable } = defaultConfig ) {
return function observableDecorator(target, key, descriptor) {
const startWith = [];
let observer = null;
const observable = Observable.create((obs) => observer = obs);
// props like `first = 'Kevin'` provide an initializer function
// to return the value;
if (typeof descriptor.initializer === 'function') {
startWith.push( descriptor.initializer() );
}
// create cache for storing observables
// so that getter / initializer functions only need to run once
if (!target._observables) {
Object.defineProperty(target, '_observables', {
enumerable: false,
value: {}
});
}
return {
get() {
const cache = target._observables;
// cache observable if not already present
if (!cache[key]) {
if (typeof descriptor.get === 'function') {
// create derived stream property using getter
//
// @observable
// get myProp() { ... }
cache[key] = fromObservable(
descriptor.get.call(target)
);
} else {
// create "simple" stream property
//
// @obserable
// first = 'Kevin';
cache[key] = fromObservable(
observable.startWith(...startWith)
);
}
}
// return value from cache
return cache[key];
},
set(val) {
if (observer) {
observer.next(val);
} else {
startWith.push(val);
}
}
};
};
}
const observableDecorator = observableFromConfig();
export default observableDecorator;