Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clear memoized for state while deferring notifications #261

Merged
merged 4 commits into from
Nov 6, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/appHost.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ export function createAppHost(initialEntryPointsOrPackages: EntryPointOrPackage[
let isInstallingEntryPoints: boolean = false
let isStoreSubscribersNotifyInProgress = false
let isObserversNotifyInProgress = false
let isDeferringNotifications = false
const entryPointsInstallationEndCallbacks: Map<string, () => void> = new Map()

verifyLayersUniqueness(options.layers)
Expand Down Expand Up @@ -665,6 +666,9 @@ miss: ${memoizedWithMissHit.miss}
},
notifyObserversIsRunning => {
isObserversNotifyInProgress = notifyObserversIsRunning
},
deferNotifications => {
isDeferringNotifications = deferNotifications
}
)
store.subscribe(() => {
Expand All @@ -675,7 +679,7 @@ miss: ${memoizedWithMissHit.miss}
})
store.syncSubscribe(() => {
shouldFlushMemoization = true
if (isStoreSubscribersNotifyInProgress || isObserversNotifyInProgress) {
if (isStoreSubscribersNotifyInProgress || isObserversNotifyInProgress || isDeferringNotifications) {
shouldFlushMemoization = false
flushMemoizedForState()
}
Expand Down
9 changes: 6 additions & 3 deletions src/throttledStore.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export interface StateContribution<TState = {}, TAction extends AnyAction = AnyA
export interface ThrottledStore<T = any> extends Store<T> {
hasPendingSubscribers(): boolean
flush(config?: { excecutionType: 'scheduled' | 'immediate' | 'default' }): void
deferSubscriberNotifications<K>(action: () => K | Promise<K>): Promise<K>
deferSubscriberNotifications<K>(action: () => K | Promise<K>, shouldClearMemoizedForState?: boolean): Promise<K>
}

export interface PrivateThrottledStore<T = any> extends ThrottledStore<T> {
Expand Down Expand Up @@ -157,7 +157,8 @@ export const createThrottledStore = (
requestAnimationFrame: Window['requestAnimationFrame'],
cancelAnimationFrame: Window['cancelAnimationFrame'],
updateIsSubscriptionNotifyInProgress: (isSubscriptionNotifyInProgress: boolean) => void,
updateIsObserversNotifyInProgress: (isObserversNotifyInProgress: boolean) => void
updateIsObserversNotifyInProgress: (isObserversNotifyInProgress: boolean) => void,
updateIsDeferringNotifications: (isDeferringNotifications: boolean) => void
): PrivateThrottledStore => {
let pendingBroadcastNotification = false
let pendingObservableNotifications: Set<AnyPrivateObservableState> | undefined
Expand Down Expand Up @@ -279,17 +280,19 @@ export const createThrottledStore = (
observableNotify: onObservableNotify,
resetPendingNotifications: resetAllPendingNotifications,
hasPendingSubscribers: () => pendingBroadcastNotification,
deferSubscriberNotifications: async action => {
deferSubscriberNotifications: async (action, shouldClearMemoizedForState) => {
ShirShintel marked this conversation as resolved.
Show resolved Hide resolved
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suggest changing to parameter to be {shouldClearMemoizedForState} as options object to allow forward compatibility.
Also, it might be misleading, since it would clear cache only on dispatch, maybe we should name it shouldDispatchClearCache or something like that

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We wanted this to be a temporary solution, so that after we make sure it does not hurt performance, we'll remove this option and do it by default. In that case, do you still want an options object?

regarding the name - changed :)

if (isDeferrringNotifications) {
return action()
}
try {
executePendingActions()
isDeferrringNotifications = true
shouldClearMemoizedForState && updateIsDeferringNotifications(isDeferrringNotifications)
const functionResult = await action()
return functionResult
} finally {
isDeferrringNotifications = false
shouldClearMemoizedForState && updateIsDeferringNotifications(isDeferrringNotifications)
executePendingActions()
}
}
Expand Down
28 changes: 28 additions & 0 deletions test/connectWithShell.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -937,6 +937,34 @@ describe('connectWithShell-useCases', () => {
expect(renderSpy).toHaveBeenCalledTimes(2)
})

it('should clear state memoization on dispatch when deferring notifications and setting shouldClearMemoizedForState', async () => {
const { host, shell } = createMocks(entryPointWithState, [entryPointSecondStateWithAPI])
let numberOfCalls = 0
const originalFn = jest.fn(() => ++numberOfCalls)
const memoizedFn = shell.memoizeForState(originalFn, () => '*') as _.MemoizedFunction
const clearCacheSpy = jest.spyOn(memoizedFn.cache, 'clear')

await host.getStore().deferSubscriberNotifications(() => {
host.getStore().dispatch({ type: 'MOCK' })
}, true)

expect(clearCacheSpy).toHaveBeenCalledTimes(1)
})

it('should not clear state memoization on dispatch when deferring notifications without setting shouldClearMemoizedForState', async () => {
const { host, shell } = createMocks(entryPointWithState, [entryPointSecondStateWithAPI])
let numberOfCalls = 0
const originalFn = jest.fn(() => ++numberOfCalls)
const memoizedFn = shell.memoizeForState(originalFn, () => '*') as _.MemoizedFunction
const clearCacheSpy = jest.spyOn(memoizedFn.cache, 'clear')

await host.getStore().deferSubscriberNotifications(() => {
host.getStore().dispatch({ type: 'MOCK' })
})

expect(clearCacheSpy).toHaveBeenCalledTimes(0)
})

it('should not mount connected component on props update', () => {
const { host, shell, renderInShellContext } = createMocks(entryPointWithState, [entryPointSecondStateWithAPI])
const ConnectedComp = connectWithShell(mapStateToProps, undefined, shell, { allowOutOfEntryPoint: true })(PureComp)
Expand Down
Loading