Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between an actor and invoking services in xstate?

I am just a little bit confused on what is the difference between actors and invoking services in xstate since they look just the same to me.

like image 948
Jay-R Joseph Gabunada Avatar asked Mar 12 '21 13:03

Jay-R Joseph Gabunada


1 Answers

The simplest explanation is that services are bound to state they are in. They are started and stopped when the machine enters/exists that state.

Actors are not bound to a certain state, they can be started and stopped when a machine enters a certain state, but they live in the context, and they are accessible to every state in your machine.

Example: child machine as service (started when the machine enters pending state, and automatically stopped when machine exists this state.

const parentMachine = Machine({
  id: 'parent',
  initial: 'pending',
  states: {
    pending: {
      invoke: {
        src: childMAchine
      }
    }
  }
});

Example: child machine as an actor, started when the machine enters waiting state, lives on the context as localOne property.

const parentMachine = Machine({
  id: 'parent',
  initial: 'waiting',
  context: {
    localOne: null
  },
  states: {
    waiting: {
      entry: assign({
        localOne: () => spawn(childMachine)
      })
    }
  }
});
like image 98
Ivan V. Avatar answered Sep 20 '22 11:09

Ivan V.