Running a function only once inside an observable

I am building an app that allows the user to edit their mesh, then take a screenshot of it. I have a situation where my save logic does not have direct access to the scene, so I am trying to use an observable for the file with the button to communicate with the scene and capture the screenshot. My issue is the callback inside of onSaveObservable.addOnce gets called multiple times if I make updates to the mesh in my scene. Is there a way to have the callback only be called once after clicking the Save button? Is there a better approach to my problem?

I have a custom observable that’s declared like this:

const onSaveObservable = new Observable();

Inside of fileA (does not have direct access to scene canvas):

<button @click="handleSave">Save</button>

const handleSave = () => {
  onSaveObservable. notifyObservers(null);

}

In my Babylon scene code fileB, I have expected it to only take one screenshot:

onSaveObservable.addOnce(() => {
Tools.CreateScreenshot(engine, scene.activeCamera as Camera, 150);
})

Difficult to understand and reproduce accurately.
so I’ll try to solve it with another proposal.

  1. Create a simple export function like this
    Can you import and use this in the corresponding button event?

  2. Make sure you do the observable constructor multiple times.

  3. You’ll also want to make sure that the execution is also nested multiple times.

  4. Can you create an example for states in PG?
    https://playground.babylonjs.com/#U3WMS5#1

Hum! Not a specialist here (not at all :wink:) but the API description lets me think that it would be a normal behavior to have this trigger multiple times. May be you could try “notifyObserversWithPromise
Else, another approach I believe would be to just add a pointerUp or trigger a variable on the button click that sets i.e. ‘screenshottaken = true’ or false if the observer/promise returns an error?

This should totally work: Babylon.js Playground

The code with addOnce might be called several times in your code. you could add a log to be sure it is not ?