Skip to content

Commit

Permalink
feat: support setting activated functions
Browse files Browse the repository at this point in the history
  • Loading branch information
jmeistrich committed Nov 22, 2023
1 parent 0b0c0b1 commit 3df8226
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 6 deletions.
4 changes: 3 additions & 1 deletion src/ObservableObject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,9 @@ function updateNodes(parent: NodeValue, obj: Record<any, any> | Array<any> | und
if (isDiff) {
// Array has a new / modified element
// If object iterate through its children
if (isPrimitive(value)) {
if (isFunction(value)) {
extractFunctionOrComputed(parent, obj, key, value);
} else if (isPrimitive(value)) {
hasADiff = true;
} else {
// Always need to updateNodes so we notify through all children
Expand Down
40 changes: 35 additions & 5 deletions tests/computedtests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
observable,
observe,
syncState,
when,
whenReady,
} from '../index';
const { globalState } = internal;
Expand Down Expand Up @@ -1181,23 +1182,32 @@ export const run = (isPersist: boolean) => {
});
test('subscription with refresh', async () => {
let num = 0;
const waiter = observable(0);
const obs = observable(
activated({
subscribe: ({ refresh }) => {
setTimeout(() => {
refresh();
}, 5);
when(
() => waiter.get() === 1,
() => {
setTimeout(() => {
refresh();
}, 0);
},
);
},
get: () =>
new Promise<string>((resolve) => {
setTimeout(() => resolve('hi there ' + num++), 0);
setTimeout(() => {
resolve('hi there ' + num++);
waiter.set((v) => v + 1);
}, 0);
}),
}),
);
expect(obs.get()).toEqual(undefined);
await promiseTimeout(0);
expect(obs.get()).toEqual('hi there 0');
await promiseTimeout(10);
await when(() => waiter.get() === 2);
expect(obs.get()).toEqual('hi there 1');
});
test('subscribe update runs after get', async () => {
Expand Down Expand Up @@ -1314,4 +1324,24 @@ export const run = (isPersist: boolean) => {
]);
});
});
describe('Set after', () => {
test('Basic computed set after', () => {
const obs = observable({ test: 10, test2: 20 });
const comp = observable();
comp.set(() => obs.test.get() + obs.test2.get());
expect(comp.get()).toEqual(30);
});
test('Basic computed set after with child', () => {
const obs = observable({ test: 10, test2: 20 });
const comp = observable<{ child: number }>();
comp.set({ child: () => obs.test.get() + obs.test2.get() });
expect(comp.child.get()).toEqual(30);
});
test('Basic computed set after with activated child', () => {
const obs = observable({ test: 10, test2: 20 });
const comp = observable<{ child: number }>();
comp.set({ child: activated({ get: () => obs.test.get() + obs.test2.get() }) });
expect(comp.child.get()).toEqual(30);
});
});
};

0 comments on commit 3df8226

Please sign in to comment.