forked from reduxjs/react-redux
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSubscription.js
74 lines (61 loc) · 1.88 KB
/
Subscription.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
74
// a linked list of nest subscription listeners. Implementing as a LL instead of an array
// makes for cheaper subscriptions & unsubscriptions vs cloning/mutating an array. Also, it
// was nice to implement a linked list for the first time in like 15 years.
function createNestedSubList() {
const head = {}
return {
subscribe(listener) {
const first = head.next
let current = head.next = { listener, prev: head, next: first }
if (first) first.prev = current
return function unsubscribe() {
if (!current) return
// unsubscribe takes itself out of the list, by updating its neighbors to point to
// each other
const { next, prev } = current
if (next) next.prev = prev
prev.next = next
current = null
}
},
notifyAll() {
let current = head.next
while (current) {
current.listener()
current = current.next
}
}
}
}
// encapsulates the subscription logic for connecting a component to the redux store, as
// well as nesting subscriptions of descendant components, so that we can ensure the
// ancestor components re-render before descendants
export default class Subscription {
constructor(store, parentSub, onStateChange) {
this.subscribe = parentSub
? parentSub.addNestedSub.bind(parentSub)
: store.subscribe
this.onStateChange = onStateChange
this.unsubscribe = null
this.nestedSubs = createNestedSubList()
}
addNestedSub(listener) {
this.trySubscribe()
return this.nestedSubs.subscribe(listener)
}
isSubscribed() {
return Boolean(this.unsubscribe)
}
trySubscribe() {
if (this.unsubscribe) return
this.unsubscribe = this.subscribe(() => {
this.onStateChange(this.nestedSubs.notifyAll)
})
}
tryUnsubscribe() {
if (this.unsubscribe) {
this.unsubscribe()
}
this.unsubscribe = null
}
}