Hacker News new | ask | show | jobs
by UberMouse 2318 days ago
> e.g. having the “NavigationService” change which links should be available by listening to a state change on the “UserSession” service as a user becomes authenticated.

Could you expand on how you're achieving this? I'm creating a new project using xState at work and this is one of the things I've been trying to come up with a solution too.

My biggest problem is the pattern I've set up for routing on top of xState (It's an electron app so no URL management required which makes that easy) requires you to create the state machine yourself, so it can't for example be used as an actor in part of a larger system.

It sounds like your NavigationService and UserSession service might be similarly separated so I'm curious how they're communicating?

Something that occurred to me last night is that I can probably make a coordinator of some sort somewhere in the tree which forwards actions from state machine to another as required.

1 comments

We keep things very simple. Maybe that will have to change as the code base grows, but for now it works and it easy to grok.

On start of the application we create singletons of our state machine backed services, and manage the dependencies between them manually. That is, we create an instance of the UserSessionService and then pass it into a "constructor" for the NavService. That constructing function creates the NavService and then wires them together by subscribing the NavService to listen to the state transitions of the UserSessionService.

I suppose if the code base grows and you have dozens of services to keep track of, it will get pretty unwieldy, but that is no different than using a fancy IOC container in Java/.Net. We plan on keeping things simple, while still braking apart the single store you'd have with Redux.

I hacked together a simple gist to show the basics of how we wire things together (without getting into the specifics of how the internals of the state machines work). [1]

[1] https://gist.github.com/adamkl/656008691d42220eddf8bfe147753...

That does help clarify things, thanks :) For context I'm just starting out this app so it's simple for now, but this is my first major project with xState so I'm trying to come up with sensible patterns.

I'll have a think about this and see if I can work it into my structure as I'm certainly going to need inter-machine communication as it grows.

The `makeMachineRoutable` function in this gist is what I'm using to consume my state machines in React. https://gist.github.com/UberMouse/49ff91e95390265d63d3ac1bc7...

It also shows my prototype for xstate based declarative data fetching, though I have sinced switched to using observables instead of promises for representing my GraphQL query results so I've changed it quite a bit.