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.
2 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)
})
}
}
});

- 7,593
- 2
- 36
- 53
Invoked services and spawned actors are both actors. Difference is in the way you create them. I'll use terms 'actor' and 'service' interchangeably, but differentiate between "invoked actor/service" and "spawned actor/service".
When machine entering the state with invoke
property, it creates service. You have to decide beforehand how many services you will invoke and what services exactly you want to invoke. When you exit state with invoked services, you will not be able to communicate with them anymore, and in some cases (invoking machines, callbacks that return cleanup function) service will be stopped and cleaned up. References to this services are kept internally. It is a good way to send requests or add some computation that you might want to opt out of, or to wait until actor is done doing it's stuff.
With spawn
action you can create any amount of actors at any time. It is not set in stone what actors you are creating, but you will have to store references to them in context. You can also stop any of spawned actors at any time. For example, you can spawn actor in one state, and stop it in some other state, or conditionally on action. It is useful when you want to have system where you can spawn or stop actors on demand at any time and don't want to be tied to specific state.
Other that that - they are same.

- 2,644
- 1
- 14
- 18