Skip to content

Commit

Permalink
Fixes #461 - Copy listeners array, so subscribes can't affect the loop.
Browse files Browse the repository at this point in the history
Unsubscribing during a dispatch would change the listeners array.
However that causes the next listener not to fire.
  • Loading branch information
arian committed Aug 11, 2015
1 parent f0132a0 commit 2ddfd71
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/createStore.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ export default function createStore(reducer, initialState) {
isDispatching = false;
}

listeners.forEach(listener => listener());
listeners.slice().forEach(listener => listener());
return action;
}

Expand Down
22 changes: 22 additions & 0 deletions test/createStore.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,28 @@ describe('createStore', () => {
expect(listenerB.calls.length).toBe(2);
});

it('should support removing a subscription within a subscription', () => {
const store = createStore(reducers.todos);
const listenerA = expect.createSpy(() => {});
const listenerB = expect.createSpy(() => {});
const listenerC = expect.createSpy(() => {});

store.subscribe(listenerA);
const unSubB = store.subscribe(() => {
listenerB();
unSubB();
});
store.subscribe(listenerC);

store.dispatch({});
store.dispatch({});

expect(listenerA.calls.length).toBe(2);
expect(listenerB.calls.length).toBe(1);
expect(listenerC.calls.length).toBe(2);

});

it('should provide an up-to-date state when a subscriber is notified', done => {
const store = createStore(reducers.todos);
store.subscribe(() => {
Expand Down

0 comments on commit 2ddfd71

Please sign in to comment.