Skip to content

Commit

Permalink
fix subscribe was able to update before get returned
Browse files Browse the repository at this point in the history
  • Loading branch information
jmeistrich committed Nov 21, 2023
1 parent 7baaa12 commit 4012734
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 3 deletions.
8 changes: 5 additions & 3 deletions src/ObservableObject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1170,9 +1170,11 @@ const activateNodeBase = (globalState.activateNode = function activateNodeBase(

if (subscribe) {
const updateFromSubscribe: UpdateFn = (params) => {
isSettingFromSubscribe = true;
update(params);
isSettingFromSubscribe = false;
whenReady(node.state!.isLoaded, () => {
isSettingFromSubscribe = true;
update(params);
isSettingFromSubscribe = false;
});
};
subscribe({ node, update: updateFromSubscribe, refresh } as SubscribeOptions);
}
Expand Down
32 changes: 32 additions & 0 deletions tests/computedtests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
observable,
observe,
syncState,
whenReady,
} from '../index';
const { globalState } = internal;

Expand Down Expand Up @@ -1199,6 +1200,37 @@ export const run = (isPersist: boolean) => {
await promiseTimeout(10);
expect(obs.get()).toEqual('hi there 1');
});
test('subscribe update runs after get', async () => {
let didGet = false;
const obs = observable(
activated({
subscribe: ({ update }) => {
setTimeout(() => {
update({ value: 'from subscribe' });
}, 0);
},
get: () => {
return new Promise<string>((resolve) => {
setTimeout(() => {
didGet = true;
resolve('hi there');
}, 5);
});
},
}),
);
expect(obs.get()).toEqual(undefined);
expect(didGet).toEqual(false);
await promiseTimeout(0);
expect(didGet).toEqual(false);
expect(obs.get()).toEqual(undefined);
await promiseTimeout(0);
expect(didGet).toEqual(false);
expect(obs.get()).toEqual(undefined);
await whenReady(obs);
expect(didGet).toEqual(true);
expect(obs.get()).toEqual('from subscribe');
});
});
describe('loading', () => {
test('isLoaded', async () => {
Expand Down

0 comments on commit 4012734

Please sign in to comment.