Dynamically create variables which are observed?

Hi, first I want to thank you all for creating this amazing tool. It surprisingly simplified my flow in many ways

Right now I am tackling with one issue

I want to use this syntax

md`

${svg`
 <svg width=200 height="200">
<rect width=100 height=${animate(100)} />
 </svg>  
`}
`

To create charts which would have corresponding properties anymated

Animate itself is an async function which yields values

But I can’t seem to make it work.

If I try to create a separate cell for this and assign function result to it

animated = animate(100)

Then it works using this syntax

 md`
${svg`
 <svg width=200 height="200">
    <rect width=100 height=${animated} />
 </svg>  
`}

`

But the thing is I don’t want to create separate cell variables when I try to animate some property (a.k.a. asynchronously assign some value )

How can I achieve the desired result?

Hi David!

Async & generator functions aren’t expanded to their values in Observable, because it’s likely that developers want to consume their outputs some other way - like with a for of loop or re-yielding their values with yield *. So calling those methods in a separate cell - as you do in this notebook - is the best way to expose the values they return, if you want to keep them as methods.

But if you don’t need them to be methods, you can use blocks instead:

animate = {
  let value = 100;
  let defaultTime = 40000;
  let defaultDelay = 10;
  let tickCounts = defaultTime/defaultDelay;
  for (let i = 0; i <= tickCounts; ++i) {
    await Promises.delay(defaultDelay);
    yield i*value/tickCounts;
  }
  yield value;
}

Blocks, unlike methods, are exposed as their values, and here’s a fork that demonstrates that in this notebook. That said, they don’t take parameters like functions do, so you wouldn’t be able to customize delay and such in the same way as you’re doing now in this notebook.

Here’s a notebook that explains the difference between generator cells, generator functions and generator objects (or generators):

1 Like

Thanks
Tom, mike

I will try to approach this topic differently