Skip to content

Commit

Permalink
WIP: cached.
Browse files Browse the repository at this point in the history
  • Loading branch information
dgp1130 committed Dec 5, 2023
1 parent 2dba984 commit 3be28bf
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/signals/cached.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { Consumer, getCurrentConsumer, Producer } from './graph.js';
import { Signal } from './types.js';

/** TODO */
export function cached<Value>(cb: () => Value): Signal<Value> {
const consumer = Consumer.from();

let value: Value;
let dirty = true;
const producer = Producer.from(() => {
if (dirty) {
value = consumer.record(cb);
dirty = false;

const currentConsumer = getCurrentConsumer();
if (currentConsumer) {
producer.addConsumer(currentConsumer);
currentConsumer.addProducer(producer);
}
}

return value;
});

consumer.listen(() => {
dirty = true;
producer.notifyConsumers();
});

return producer.poll.bind(producer);
}
1 change: 1 addition & 0 deletions src/signals/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export { cached } from './cached.js';
export { effect } from './effect.js';
export { signal } from './signal.js';
export { Signal, WriteableSignal } from './types.js';

0 comments on commit 3be28bf

Please sign in to comment.