Skip to content

Commit

Permalink
Merge pull request #462 from arian/fix-461-unsubscribing-listeners
Browse files Browse the repository at this point in the history
Fixes #461 - Copy listeners array, so subscribes can't affect the loop.
  • Loading branch information
gaearon committed Aug 11, 2015
2 parents f0132a0 + 2ddfd71 commit d594232
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 d594232

Please sign in to comment.