DEV Community

Discussion on: Building a Reactive Library from Scratch

Collapse
 
goldeli profile image
缪宇 • Edited

Hey Ryan, If I change [...subscriptions] to subscriptions. it will causes infinite loop.

  const write = (nextValue) => {
    value = nextValue;

    for (const sub of [...subscriptions]) {
      sub.execute();
    }
  };
Enter fullscreen mode Exit fullscreen mode

to

  const write = (nextValue) => {
    value = nextValue;

    for (const sub of subscriptions) {
      sub.execute();
    }
  };
Enter fullscreen mode Exit fullscreen mode

Error:

What is the cause? Thank you so much. Full Code

Collapse
 
ryansolid profile image
Ryan Carniato

Yep. It's because the first thing each computation execution does is remove itself from the subscription list and then during the process of execution if it reads the same signal it adds itself back on. What this means is if we don't clone the original list, while iterating over it the process of executing the computation will cause it to end up at the end of the list. And it will then execute it again within the same loop, and add itself to the end of the list and so on.