Skip to content

Commit

Permalink
refactor(store/enhancers): use weakMemo
Browse files Browse the repository at this point in the history
  • Loading branch information
exuanbo committed Dec 17, 2023
1 parent 3ad4f1e commit e5d74ee
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 26 deletions.
10 changes: 4 additions & 6 deletions src/app/store/observers/actionObserver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
import { filter, map, type Observable, Subject } from 'rxjs'

import { injectStoreExtension } from '../enhancers/injectStoreExtension'
import { createWeakCache } from './weakCache'
import { weakMemo } from './weakMemo'

type ObserveAction = <Payload>(actionCreator: PayloadActionCreator<Payload>) => Observable<Payload>

Expand All @@ -36,11 +36,9 @@ export const createActionObserver = (): ActionObserver => {
return result
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const cache = createWeakCache<PayloadActionCreator<any>>()

const onAction: ObserveAction = (actionCreator) =>
cache(actionCreator, () => action$.pipe(filter(matchType(actionCreator)), map(getPayload)))
const onAction: ObserveAction = weakMemo((actionCreator) =>
action$.pipe(filter(matchType(actionCreator)), map(getPayload)),
)

const enhancer = injectStoreExtension(() => ({ onAction }))

Expand Down
9 changes: 4 additions & 5 deletions src/app/store/observers/stateObserver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { BehaviorSubject, distinctUntilChanged, map, type Observable } from 'rxj
import { invariant } from '@/common/utils'

import { injectStoreExtension } from '../enhancers/injectStoreExtension'
import { createWeakCache } from './weakCache'
import { weakMemo } from './weakMemo'

type ObserveState<State> = <Selected>(selector: Selector<State, Selected>) => Observable<Selected>

Expand Down Expand Up @@ -32,10 +32,9 @@ export const createStateObserver = <State>(): StateObserver<State> => {
}
}

const cache = createWeakCache<Selector<State, unknown>>()

const onState: ObserveState<State> = (selector) =>
cache(selector, () => distinctState$.pipe(map(selector), distinctUntilChanged()))
const onState: ObserveState<State> = weakMemo((selector) =>
distinctState$.pipe(map(selector), distinctUntilChanged()),
)

const enhancer = injectStoreExtension(() => ({ onState }))

Expand Down
15 changes: 0 additions & 15 deletions src/app/store/observers/weakCache.ts

This file was deleted.

9 changes: 9 additions & 0 deletions src/app/store/observers/weakMemo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export const weakMemo = <Arg extends WeakKey, Result>(fn: (arg: Arg) => Result): typeof fn => {
const cache = new WeakMap<Arg, Result>()
return (arg) => {
if (!cache.has(arg)) {
cache.set(arg, fn(arg))
}
return cache.get(arg)!
}
}

0 comments on commit e5d74ee

Please sign in to comment.