forked from reduxjs/react-redux
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSubscription.js
61 lines (51 loc) · 1.51 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
// 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) {
this.subscribe = parentSub
? parentSub.addNestedSub.bind(parentSub)
: store.subscribe.bind(store)
this.unsubscribe = null
this.nextListeners = this.currentListeners = []
}
ensureCanMutateNextListeners() {
if (this.nextListeners === this.currentListeners) {
this.nextListeners = this.currentListeners.slice()
}
}
addNestedSub(listener) {
this.trySubscribe()
let isSubscribed = true
this.ensureCanMutateNextListeners()
this.nextListeners.push(listener)
return function unsubscribe() {
if (!isSubscribed) return
isSubscribed = false
this.ensureCanMutateNextListeners()
const index = this.nextListeners.indexOf(listener)
this.nextListeners.splice(index, 1)
}
}
notifyNestedSubs() {
const listeners = this.currentListeners = this.nextListeners
const length = listeners.length
for (let i = 0; i < length; i++) {
listeners[i]()
}
}
isSubscribed() {
return Boolean(this.unsubscribe)
}
trySubscribe() {
if (!this.unsubscribe) {
this.unsubscribe = this.subscribe(this.onStateChange)
}
}
tryUnsubscribe() {
if (this.unsubscribe) {
this.unsubscribe()
}
this.unsubscribe = null
}
}