1 | import {
|
2 | IDerivationState_,
|
3 | IObservable,
|
4 | IDerivation,
|
5 | createInstanceofPredicate,
|
6 | endBatch,
|
7 | getNextId,
|
8 | noop,
|
9 | onBecomeObserved,
|
10 | onBecomeUnobserved,
|
11 | propagateChanged,
|
12 | reportObserved,
|
13 | startBatch,
|
14 | Lambda
|
15 | } from "../internal"
|
16 |
|
17 | export const $mobx = Symbol("mobx administration")
|
18 |
|
19 | export interface IAtom extends IObservable {
|
20 | reportObserved(): boolean
|
21 | reportChanged()
|
22 | }
|
23 |
|
24 | export class Atom implements IAtom {
|
25 | isPendingUnobservation_ = false
|
26 | isBeingObserved_ = false
|
27 | observers_ = new Set<IDerivation>()
|
28 |
|
29 | diffValue_ = 0
|
30 | lastAccessedBy_ = 0
|
31 | lowestObserverState_ = IDerivationState_.NOT_TRACKING_
|
32 | |
33 |
|
34 |
|
35 |
|
36 | constructor(public name_ = __DEV__ ? "Atom@" + getNextId() : "Atom") {}
|
37 |
|
38 |
|
39 | public onBOL: Set<Lambda> | undefined
|
40 |
|
41 | public onBUOL: Set<Lambda> | undefined
|
42 |
|
43 | public onBO() {
|
44 | if (this.onBOL) {
|
45 | this.onBOL.forEach(listener => listener())
|
46 | }
|
47 | }
|
48 |
|
49 | public onBUO() {
|
50 | if (this.onBUOL) {
|
51 | this.onBUOL.forEach(listener => listener())
|
52 | }
|
53 | }
|
54 |
|
55 | |
56 |
|
57 |
|
58 |
|
59 | public reportObserved(): boolean {
|
60 | return reportObserved(this)
|
61 | }
|
62 |
|
63 | |
64 |
|
65 |
|
66 | public reportChanged() {
|
67 | startBatch()
|
68 | propagateChanged(this)
|
69 | endBatch()
|
70 | }
|
71 |
|
72 | toString() {
|
73 | return this.name_
|
74 | }
|
75 | }
|
76 |
|
77 | export const isAtom = createInstanceofPredicate("Atom", Atom)
|
78 |
|
79 | export function createAtom(
|
80 | name: string,
|
81 | onBecomeObservedHandler: () => void = noop,
|
82 | onBecomeUnobservedHandler: () => void = noop
|
83 | ): IAtom {
|
84 | const atom = new Atom(name)
|
85 |
|
86 | if (onBecomeObservedHandler !== noop) {
|
87 | onBecomeObserved(atom, onBecomeObservedHandler)
|
88 | }
|
89 |
|
90 | if (onBecomeUnobservedHandler !== noop) {
|
91 | onBecomeUnobserved(atom, onBecomeUnobservedHandler)
|
92 | }
|
93 | return atom
|
94 | }
|