Skip to content

Commit

Permalink
refactor(store): action and state observers use WeakMap
Browse files Browse the repository at this point in the history
  • Loading branch information
exuanbo committed Dec 6, 2023
1 parent cf8b44d commit 83db6a6
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
13 changes: 11 additions & 2 deletions src/app/actionObserver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,17 @@ export const createActionObserver = (): ActionObserver => {
return result
}

const onAction: OnAction = (actionCreator) =>
action$.pipe(filter(matchType(actionCreator)), map(getPayload))
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const payload$Map = new WeakMap<PayloadActionCreator<any>, Observable<any>>()

const onAction: OnAction = (actionCreator) => {
let payload$ = payload$Map.get(actionCreator)
if (!payload$) {
payload$ = action$.pipe(filter(matchType(actionCreator)), map(getPayload))
payload$Map.set(actionCreator, payload$)
}
return payload$
}

return {
middleware,
Expand Down
13 changes: 11 additions & 2 deletions src/app/stateObserver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,17 @@ export const createStateObserver = <TState>(): StateObserver<TState> => {
}
}

const onState: OnState<TState> = (selector, { initial = false } = {}) =>
distinctState$.pipe(map(selector), distinctUntilChanged(), initial ? identity : skip(1))
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const selected$Map = new WeakMap<Selector<TState, unknown>, Observable<any>>()

const onState: OnState<TState> = (selector, { initial = false } = {}) => {
let selected$ = selected$Map.get(selector)
if (!selected$) {
selected$ = distinctState$.pipe(map(selector), distinctUntilChanged())
selected$Map.set(selector, selected$)
}
return selected$.pipe(initial ? identity : skip(1))
}

return {
middleware,
Expand Down

0 comments on commit 83db6a6

Please sign in to comment.