tc39 / proposal-signals

A proposal to add signals to JavaScript.
MIT License
2.87k stars 54 forks source link

Method to return cache status along with `.get()` #186

Closed dead-claudia closed 3 weeks ago

dead-claudia commented 3 weeks ago

Maybe something like a signal.checkedGet(): {isCached, value}. (Admittedly, the name is awful.)

R2D221 commented 3 weeks ago

What would value return when isCached is false?

dead-claudia commented 3 weeks ago

@R2D221 In both cases, value would be the same as you'd get from .get(). The only extra functionality is .isCached (or whatever it gets named) telling you if it's a "new" value that was just calculated.

shaylew commented 3 weeks ago

Unless you have exclusive read access to the Computed, isCached ("wasCached"?) is tricky to interpret. Some other reader may have already forced it to recompute, so just that one bit for "did it change just now?" isn't enough to tell whether it changed since this particular reader last read it.

We tried not to surface timestamps in the public API, but the more general tool here is really signal.lastChanged (for global timestamps) or signal.versionNumber (for local version counters). Either one lets you ask "has this signal changed since I last checked" in a way that's still stable with multiple readers. AFAIK every signals system with multiple consumers either uses some sort of version number or some sort of synchronous "change notifications" (some have both) in order to handle checking whether a Computed needs to rerun.

Given that this notion of versions/time is indispensable in the implementation, I wonder if it makes sense to expose it to consumers? But it's not entirely clear to me yet what a minimal surface area would be for this extension.

dead-claudia commented 3 weeks ago

@shaylew That's a good point. I'll close.