Skip to content

Commit 1c73295

Browse files
committed
Add subscribe to listenerApi
1 parent d0cc194 commit 1c73295

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

packages/action-listener-middleware/src/index.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,7 @@ export interface ActionListenerMiddlewareAPI<S, D extends Dispatch<AnyAction>>
110110
extends MiddlewareAPI<D, S> {
111111
getOriginalState: () => S
112112
unsubscribe(): void
113+
subscribe(): void
113114
condition: ConditionFunction<S>
114115
currentPhase: MiddlewarePhase
115116
// TODO Figure out how to pass this through the other types correctly
@@ -479,6 +480,9 @@ export function createActionListenerMiddleware<
479480
currentPhase,
480481
extra,
481482
unsubscribe: entry.unsubscribe,
483+
subscribe: () => {
484+
listenerMap.set(entry.id, entry)
485+
},
482486
})
483487
} catch (listenerError) {
484488
safelyNotifyError(onError, listenerError)

packages/action-listener-middleware/src/tests/listenerMiddleware.test.ts

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ const middlewareApi = {
2727
dispatch: expect.any(Function),
2828
currentPhase: expect.stringMatching(/beforeReducer|afterReducer/),
2929
unsubscribe: expect.any(Function),
30+
subscribe: expect.any(Function),
3031
}
3132

3233
const noop = () => {}
@@ -419,6 +420,36 @@ describe('createActionListenerMiddleware', () => {
419420
])
420421
})
421422

423+
test('Can re-subscribe via middleware api', async () => {
424+
let numListenerRuns = 0
425+
middleware.addListener({
426+
actionCreator: testAction1,
427+
listener: async (action, listenerApi) => {
428+
numListenerRuns++
429+
430+
listenerApi.unsubscribe()
431+
432+
await listenerApi.condition(testAction2.match)
433+
434+
listenerApi.subscribe()
435+
},
436+
})
437+
438+
store.dispatch(testAction1('a'))
439+
expect(numListenerRuns).toBe(1)
440+
441+
store.dispatch(testAction1('a'))
442+
expect(numListenerRuns).toBe(1)
443+
444+
store.dispatch(testAction2('b'))
445+
expect(numListenerRuns).toBe(1)
446+
447+
await delay(5)
448+
449+
store.dispatch(testAction1('b'))
450+
expect(numListenerRuns).toBe(2)
451+
})
452+
422453
const whenMap: [When, string, string, number][] = [
423454
[undefined, 'reducer', 'listener', 1],
424455
['beforeReducer', 'listener', 'reducer', 1],

0 commit comments

Comments
 (0)