Skip to content

Commit

Permalink
Data: Standardize on snapshotting behavior
Browse files Browse the repository at this point in the history
  • Loading branch information
aduth committed Feb 28, 2018
1 parent dde60a8 commit ff8516b
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 9 deletions.
8 changes: 1 addition & 7 deletions data/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,7 @@ let listeners = [];
* Global listener called for each store's update.
*/
export function globalListener() {
// Use for loop instead of Array#forEach, as it's possible a listener's
// behavior causes one further in the stack to be unsubscribed. The
// latter's callback should not be called, which requires monitoring
// changes to the array as they occur in iteration.
for ( let i = 0; i < listeners.length; i++ ) {
listeners[ i ]();
}
listeners.forEach( ( listener ) => listener() );
}

/**
Expand Down
18 changes: 16 additions & 2 deletions data/test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,21 @@ describe( 'subscribe', () => {
expect( incrementedValue ).toBe( 3 );
} );

it( 'avoids calling a later listener if unsubscribed during earlier callback', () => {
it( 'snapshots listeners on change, avoiding a later listener if subscribed during earlier callback', () => {
const store = registerReducer( 'myAwesomeReducer', ( state = 0 ) => state + 1 );
const secondListener = jest.fn();
const firstListener = jest.fn( () => {
subscribeWithUnsubscribe( secondListener );
} );

subscribeWithUnsubscribe( firstListener );

store.dispatch( { type: 'dummy' } );

expect( secondListener ).not.toHaveBeenCalled();
} );

it( 'snapshots listeners on change, calling a later listener even if unsubscribed during earlier callback', () => {
const store = registerReducer( 'myAwesomeReducer', ( state = 0 ) => state + 1 );
const firstListener = jest.fn( () => {
secondUnsubscribe();
Expand All @@ -260,7 +274,7 @@ describe( 'subscribe', () => {

store.dispatch( { type: 'dummy' } );

expect( secondListener ).not.toHaveBeenCalled();
expect( secondListener ).toHaveBeenCalled();
} );
} );

Expand Down

0 comments on commit ff8516b

Please sign in to comment.