xstate icon indicating copy to clipboard operation
xstate copied to clipboard

rehydrating stopped actors fail to subscribe

Open christophe-g opened this issue 2 years ago • 2 comments

Bug or feature request?

Bug

Description:

rehydrating a stopped actor and then subscribing again will not work

 const actor = createActor(machine).start();
 actor.stop();
 const persistedState = actor.getPersistedSnapshot();
 const rehydratedActor = createActor(machine, {
    snapshot: persistedState
  }).start();

  // SPY IS NEVER CALLED
  // -------------------------------
  rehydratedActor.subscribe((snap) => spy())

 rehydratedActor.send({
        type: 'NEXT'
      })

(Bug) Expected result:

stopped rehydrated actors can be subscribed to.

(Bug) Actual result:

They cannot.

(Bug) Potential fix:

persisted state status must be set as active prior to rehydrating the actor:

...
 const persistedState = actor.getPersistedSnapshot();
 const rehydratedActor = createActor(machine, {
    snapshot: {...persistedState, status: 'active'}
  }).start();

...

Link to reproduction or proof-of-concept:

New test in https://github.com/statelyai/xstate/pull/4582

christophe-g avatar Dec 11 '23 16:12 christophe-g

It might not be super clear (so we should think about what to do about it) but you should persist the snapshot before stopping the actor. The problem is that you persisted a stopped snapshot while you have wanted an active one.

Andarist avatar Dec 11 '23 18:12 Andarist

Thanks @Andarist

It might not be super clear (so we should think about what to do about it)

I agree, it is not clear - took me ages to understand what was going on in a real-world-a-bit-more-complex use case. ; )

Would be quite helpful to have a warning in this case.

christophe-g avatar Dec 11 '23 18:12 christophe-g