diff --git a/src/data-store.spec.ts b/src/data-store.spec.ts index c9d4605..2f17831 100644 --- a/src/data-store.spec.ts +++ b/src/data-store.spec.ts @@ -179,6 +179,32 @@ describe('DataStore', () => { ]); }); + it('execute thunk actions sequentially', async () => { + const initialState = { count: 0 }; + const store = new DataStore((state = initialState, action) => { + if (action.type === 'UPDATE') { + return { ...state, count: action.payload }; + } + + return state; + }, initialState); + + const thunk = (readableStore: ReadableDataStore<{ count: number }>) => { + const { count } = readableStore.getState(); + + return Observable.of({ type: 'UPDATE', payload: count + 1 }) + .delay(10); + }; + + await Promise.all([ + store.dispatch(thunk), + store.dispatch(thunk), + store.dispatch(thunk), + ]); + + expect(store.getState()).toEqual({ count: 3 }); + }); + it('resolves promises sequentially', async () => { const store = new DataStore((state = {}) => state); const callback = jest.fn(); diff --git a/src/data-store.ts b/src/data-store.ts index def6853..aa43102 100644 --- a/src/data-store.ts +++ b/src/data-store.ts @@ -1,4 +1,5 @@ import { isEqual, merge } from 'lodash'; +import { defer } from 'rxjs/observable/defer'; import { from } from 'rxjs/observable/from'; import { of } from 'rxjs/observable/of'; import { _throw } from 'rxjs/observable/throw'; @@ -202,7 +203,7 @@ export default class DataStore, options: DispatchOptions = {} ): Promise { - return this._dispatchObservableAction(thunkAction(this), options); + return this._dispatchObservableAction(defer(() => thunkAction(this)), options); } private _getDispatcher(queueId: string = 'default'): Dispatcher {