const lastStateContainer = {}

function _observable(store, keyPath, callback) {
  return store.subscribe(() => {
    const newState = store.getState().getIn(keyPath)
    const keyPathStr = keyPath.join('')
    if (lastStateContainer[keyPathStr] !== newState) {
      const _lastState = lastStateContainer[keyPathStr]
      lastStateContainer[keyPathStr] = newState
      callback(newState, _lastState)
    }
  })
}

export default function createObserveble(store, keyPath) {
  let subscribeId = 0

  return {
    subscribe: callback => {
      subscribeId = _observable(store, keyPath, callback)
    },
    unSubscribe: () => {
      store.unsubscribe(subscribeId)
    },
  }
}
