All files / src/connect/utils Subscription.js

95% Statements 38/40
78.57% Branches 11/14
75% Functions 6/8
97.3% Lines 36/37
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 75 76 77 78 79 80 81 821x 1x     31x 31x   31x   9x 9x       27x 27x 10x                 7x 7x 7x   7x 3x 1x   1x 1x             31x 31x 31x 31x 31x 31x       7x 7x       27x       1x       38x 31x       31x         9x 9x 9x 9x 9x        
const CLEARED = null
const nullListeners = { notify() {} }
 
function createListenerCollection() {
  let current = []
  let next = []
 
  return {
    clear() {
      next = CLEARED
      current = CLEARED
    },
 
    notify() {
      const listeners = current = next
      for (let i = 0; i < listeners.length; i++) {
        listeners[i]()
      }
    },
 
    get() {
      return next
    },
 
    subscribe(listener) {
      let isSubscribed = true
      Iif (next === current) next = current.slice()
      next.push(listener)
 
      return function unsubscribe() {
        if (!isSubscribed || current === CLEARED) return
        isSubscribed = false
 
        Eif (next === current) next = current.slice()
        next.splice(next.indexOf(listener), 1)
      }
    }
  }
}
 
export default class Subscription {
  constructor(store, parentSub, onStateChange) {
    this.store = store
    this.parentSub = parentSub
    this.onStateChange = onStateChange
    this.unsubscribe = null
    this.listeners = nullListeners
  }
 
  addNestedSub(listener) {
    this.trySubscribe()
    return this.listeners.subscribe(listener)
  }
 
  notifyNestedSubs() {
    this.listeners.notify()
  }
 
  isSubscribed() {
    return Boolean(this.unsubscribe)
  }
 
  trySubscribe() {
    if (!this.unsubscribe) {
      this.unsubscribe = this.parentSub
        ? this.parentSub.addNestedSub(this.onStateChange)
        : this.store.subscribe(this.onStateChange)
 
      this.listeners = createListenerCollection()
    }
  }
 
  tryUnsubscribe() {
    Eif (this.unsubscribe) {
      this.unsubscribe()
      this.unsubscribe = null
      this.listeners.clear()
      this.listeners = nullListeners
    }
  }
}