DEV Community

Discussion on: Building a Reactive Library from Scratch

Collapse
 
ryansolid profile image
Ryan Carniato

The observer pattern is inherently leaky. Signals don't need cleanup but any subscription does. If the signal outlives the subscriber it will have no longer relevant subscriptions. At minimum we need to mark the subscriber as dead. The fact that we dynamically create and tear down subscriptions on each run has us doing this work anyway. Consider this example:

const [a] = createSignal()
const [b] = createSignal()
createEffect(() => {
  console.log(a()); // track a
  createEffect(() => {
    console.log(b()); // track b
  })
})
Enter fullscreen mode Exit fullscreen mode

Every time a changes you are creating a new reaction that listens to b. So a naive approach that didn't do cleanup would just keep appending more subscriptions to b. So if you updated a 3 times b would end up with 4 subscriptions. When you updated b it would console.log 4 times.

Collapse
 
piotrnajda3000 profile image
piotrnajda3000

Hey Ryan, thank you for the article series!

In the case of the demo you've built up in this article, the b would console.log 4 times. You writing "the fact that we dynamically create and tear down subscriptions on each run has us doing this work anyway," made me think it's not supposed to happen. But, it seems to make sense: each time a changes, a new effect is created, and so the b's will stack up.

I've read that with solid the nested effect, "would be disposed on each rerun of the "parent" effect. Is this what happens in Solid, that doesn't happen in this article?

Thank you.