How to plug external services into a state machine? #1292
Unanswered
HerbCaudill
asked this question in
General
Replies: 2 comments 2 replies
-
Using an invoked callback would work best here: import { createMachine, actions } from 'xstate';
const sendMessage = message => actions.send({ type: 'sendMessage', message }, { to: 'auth' });
const machine = createMachine({
invoke: {
id: 'auth',
src: () => (cb, receive) => {
const authProtocol = ...
receive(e => {
if (e.type === 'sendMessage') {
authProtocol.sendMessage(e.message);
}
});
// ...
}
},
// ...
on: {
CLICK: { actions: sendMessage('clicked') }
}
}
}); |
Beta Was this translation helpful? Give feedback.
1 reply
-
Trying again with many fewer lines of sample code! 😀 The solution I've come up with is to wrap my state machine in a class, and to provide export class ConnectionService {
private sendMessage
constructor(sendMessage) {
this.sendMessage = sendMessage
}
public start = () => {
const machine = createMachine(
{
// ... XState config
},
{
actions: {
someAction: (context, event) => {
// ...
this.sendMessage(...)
},
}
)
const service = interpret(machine)
return service.start()
}
}
} This way whoever is consuming my const sendMessage = message => {
// ... developer implements message sending here - could be WebSocket, WebRTC, carrier pigeon, etc.
}
const alice = new ConnectionService(sendMessage).start() Again - this works, but feels non-idiomatic. Is there a more natural way to do this in XState? |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I'm using Xstate to model a peer-to-peer authentication protocol. It's network-agnostic, so for example you'd need to provide it with a
sendMessage
function that you've wired up to an existing communications channel (WebSocket, WebRTC, etc).I've stubbed out different actions like
claimIdentity
andchallengeClaim
etc. that would callsendMessage
.What's the correct way to allow the developer to provide their own
sendMessage
function?Options I've considered:
sendMessage
action, with the expectation that the developer will override it using.withConfig()
(although I haven't figured out how to invoke one action from another one, or if that's even a thing)sendMessage
functionBeta Was this translation helpful? Give feedback.
All reactions