draw Plot after some event

hi! i am trying to plot an array of values generated using the popmotion library (the values model a motion curve). see: SpringSolver2 / Sai Perchard / Observable

it seems that Plot executes immediately, before the array of motion values has been generated. i’ve tried a number of workarounds, but all of them seemed like they were adding a lot of complexity to something i assume/hope has a simple solution!

for example, i put the call to Plot in an onComplete callback provided by popmotion. but, it seems like it is not possible to use Plot in regular JS (possibly it’s a special Observable object?)

any help appreciated!

You could make arr a view and then have onComplete dispatch an event to let the plot know it’s time to resolve. Here’s an example:

Note that I constructed an HTMLElement simply to have access to dispatchEvent. I do wonder if there’s a more natural way?

Hi @perchard! You can reach into the toolbox provided by Observable’s builtin Standard Library and use Generators.observe():

arr = Generators.observe(notify => {
  const arr = [];
  popmotion.animate({
    from: 0,
    to: 100,
    onUpdate: (latest) => {
      arr.push(latest);
      notify(arr);
    }
  }); 
})

This turns your cell into a Generator that produces a new value (the updated array) on every animation update.

If you just want to wait for the end of the animation, you can have your cell return a promise that resolves on completion:

arr = new Promise(resolve => {
  const arr = [];
  popmotion.animate({
    from: 0,
    to: 100,
    onUpdate: (latest) => arr.push(latest),
    onComplete: () => resolve(arr)
  });
})

@mootari Ooh, that is nice! That way you can watch the path as it’s generated.

@mcmcclur thank you for that example. I started to go down this path (using a view) but never quite got to a working solution, so it’s nice to see how this could work!

@mootari thank you for the elegant solution - a generator is not something I have even encountered before, so definitely wouldn’t have thought of this! I also wasn’t aware of the stdlib, although I was using a few things from it that I’d seen in other notebooks. Handy to know about that and have the docs.

Appreciate the help!

This is definitely possible and encouraged, see the “Installing” section of the documentation.