#Preventing memory leaks while spawning child machines

1 messages · Page 1 of 1 (latest)

stray cobalt
#

Scenario: the child needs the parentRef in its own context to send some stuff. And the parent has the childRef in its own context, cause I spawned via 'spawn' and not 'spawnChild' (maybe this is not recommended, but I wonder why there is a 'spawn' after all?)
Is it true, that you have to do two things, when spawning child machines, to prevent memory leaks:

  1. when stopping the child, setting the parentRef to null
  2. when saving the childRef in context of parent machine, setting the childRef after stopping machine to null, and not just using spawnChild

It all sounds like a lot of boilerplate code - am I missing something?

// in child machine, while spawning the child, saving the parentRef in context 
createMachine({
  id: "childMachine",
  context: ({ input: { parentRef } }) => ({
    parentRef
})
// in child machine before stopping the child setting the parentRef to null to prevent memory leaks
createMachine({
  id: "childMachine",
   on: {
        STOP: {
          actions: [
          assign({
            parentRef: null,
      })]
    }
  })
})
// in parent machine setting the childRef to null after stopping machine to prevent memory leaks
createMachine({
  id: "parentMachine",
  on: {
        STOP_CHLD: {
          actions: [
          stopChild("childMachine")
          assign({
            childref: null,
      })]
    }
  })
narrow oak
#

It is some boilerplate code; apologies for that. But it's sorta necessary right now because JS has no way of knowing where an object is to stop/delete itself, at least not efficiently (if that makes sense)

#

In other words, if you had:

const children = {
  actor: someActor
}

actor.stop(); // still exists on children.actor

It may not be possible to do "automatic deletion"

#

Likewise, if you do

delete children.actor;

There is no "when property is deleted, do this first" unless we use proxies

violet moth
#

Could maybe use system to send event event and just keep the systemId in the context ?