Skip to content

Commit

Permalink
Clear state on teardown, make grace optional (#377)
Browse files Browse the repository at this point in the history
  • Loading branch information
bramkragten authored Jun 27, 2023
1 parent 966c685 commit ace1532
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
8 changes: 6 additions & 2 deletions lib/collection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ export const getCollection = <State>(
subscribeUpdates?: (
conn: Connection,
store: Store<State>
) => Promise<UnsubscribeFunc>
) => Promise<UnsubscribeFunc>,
options: { unsubGrace: boolean } = { unsubGrace: true }
): Collection<State> => {
if (conn[key]) {
return conn[key];
Expand Down Expand Up @@ -93,6 +94,7 @@ export const getCollection = <State>(
unsubProm.then((unsub) => {
unsub();
});
store.clearState();
conn.removeEventListener("ready", refresh);
conn.removeEventListener("disconnected", handleDisconnect);
};
Expand Down Expand Up @@ -149,7 +151,9 @@ export const getCollection = <State>(
}

if (!active) {
scheduleTeardownUpdateSubscription();
options.unsubGrace
? scheduleTeardownUpdateSubscription()
: teardownUpdateSubscription();
}
};
},
Expand Down
7 changes: 6 additions & 1 deletion lib/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export type Store<State> = {
state: State | undefined;
action(action: Action<State>): BoundAction<State>;
setState(update: Partial<State>, overwrite?: boolean): void;
clearState(): void;
subscribe(listener: Listener<State>): UnsubscribeFunc;
};

Expand Down Expand Up @@ -82,12 +83,16 @@ export const createStore = <State>(state?: State): Store<State> => {
*/
setState,

clearState() {
state = undefined;
},

/**
* Register a listener function to be called whenever state is changed. Returns an `unsubscribe()` function.
* @param {Function} listener A function to call when state changes. Gets passed the new state.
* @returns {Function} unsubscribe()
*/
subscribe(listener: Listener<State>) {
subscribe(listener: Listener<State>): UnsubscribeFunc {
listeners.push(listener);
return () => {
unsubscribe(listener);
Expand Down

0 comments on commit ace1532

Please sign in to comment.