Have a generator based upon a mutable value

Hello,

I’m trying to use Observable to visualize an experiment with a user-controlled number of runs. Basically upon a click of a button, the user can increase the number of runs.

In a different question, I asked about being able to update experiment results in an object and whether mutable applies to that data.

In this question, I’m trying to find a workaround if mutable does not apply. The way I was thinking about it is to have a generator function that basically yields the most up to date experiment result state, i.e. it’s kept internally in the generator. So there would be a mutable runs = 0 variable, that if mutated to greater than 0, would cause the generator to “do work” and yield updated results.

I might totally misunderstand how generators are supposed to work, but I would have expected the following notebook to succeed:

Thanks for writing — you ran into a bug that would occur whenever you tried to reference both value and mutable value from the same cell. (Or value and viewof value from the same cell.)

We’ve fixed it this afternoon, and cells that reference both are working properly.

Here’s a forked version of your notebook that counts down and reacts to changes in runsLeft, while counting up totalRuns. Note that because the cell doing the counting depends on runsLeft, you don’t actually need a while loop. Every time the value of runsLeft changes, the cell will be evaluated again. You also don’t need to write an explicit generator function: you can just yield.

https://beta.observablehq.com/@jashkenas/generator-test-forked-example-for-the-forum

Cheers!

Wow, that was the best possible answer I could have asked for, thanks!