Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

enhancement: store.subscribe(listener, filter) #2814

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 20 additions & 5 deletions src/createStore.js
Original file line number Diff line number Diff line change
Expand Up @@ -98,11 +98,17 @@ export default function createStore(reducer, preloadedState, enhancer) {
* @param {Function} listener A callback to be invoked on every dispatch.
* @returns {Function} A function to remove this change listener.
*/
function subscribe(listener) {
function subscribe(listener, filter) {
if (typeof listener !== 'function') {
throw new Error('Expected the listener to be a function.')
}

if (typeof filter !== 'function') {
filter = filter === true ? pure_filter : false
}

const nextListener = { listener, filter }

if (isDispatching) {
throw new Error(
'You may not call store.subscribe() while the reducer is executing. ' +
Expand All @@ -115,7 +121,7 @@ export default function createStore(reducer, preloadedState, enhancer) {
let isSubscribed = true

ensureCanMutateNextListeners()
nextListeners.push(listener)
nextListeners.push(nextListener)

return function unsubscribe() {
if (!isSubscribed) {
Expand All @@ -132,11 +138,15 @@ export default function createStore(reducer, preloadedState, enhancer) {
isSubscribed = false

ensureCanMutateNextListeners()
const index = nextListeners.indexOf(listener)
const index = nextListeners.indexOf(nextListener)
nextListeners.splice(index, 1)
}
}

function pure_filter(oldState, newState) {
return oldState === newState
}

/**
* Dispatches an action. It is the only way to trigger a state change.
*
Expand Down Expand Up @@ -181,6 +191,8 @@ export default function createStore(reducer, preloadedState, enhancer) {
throw new Error('Reducers may not dispatch actions.')
}

const oldState = currentState

try {
isDispatching = true
currentState = currentReducer(currentState, action)
Expand All @@ -190,8 +202,11 @@ export default function createStore(reducer, preloadedState, enhancer) {

const listeners = (currentListeners = nextListeners)
for (let i = 0; i < listeners.length; i++) {
const listener = listeners[i]
listener()
const { listener, filter } = listeners[i]
const apply_filter = filter && filter(oldState, currentState)
if (!apply_filter) {
listener()
}
}

return action
Expand Down