Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/release-nested-spawn-gate.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"effect-machine": patch
---

Allow nested actors to start before their parent spawn returns.
17 changes: 8 additions & 9 deletions src/actor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1262,10 +1262,6 @@ const make = Effect.fn("effect-machine.actorSystem.make")(function* () {
actorRef = actor as unknown as ActorRef<AnyState, unknown>;
// Register before start — actor is in the map before lifecycle hooks fire
yield* registerActor(id, actor);
// Auto-start: system.spawn returns a running actor
yield* actor.start.pipe(
Effect.catchCause((cause) => actor.stop.pipe(Effect.andThen(Effect.failCause(cause)))),
);
return actor;
});

Expand All @@ -1282,11 +1278,14 @@ const make = Effect.fn("effect-machine.actorSystem.make")(function* () {
options?: SystemSpawnOptions<S, E, Input>,
): Effect.Effect<ActorRef<S, E, Output>, DuplicateActorError, R> => {
const id = actorSystemId(idOrKey);
return withSpawnGate(spawnRegular(id, machine, options)) as Effect.Effect<
ActorRef<S, E, Output>,
DuplicateActorError,
R
>;
return withSpawnGate(spawnRegular(id, machine, options)).pipe(
Effect.flatMap((actor) =>
actor.start.pipe(
Effect.catchCause((cause) => actor.stop.pipe(Effect.andThen(Effect.failCause(cause)))),
Effect.as(actor),
),
),
) as Effect.Effect<ActorRef<S, E, Output>, DuplicateActorError, R>;
};

function get<S extends AnyState, E, Output>(
Expand Down
24 changes: 24 additions & 0 deletions test/actor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,30 @@ describe("ActorSystem", () => {
}).pipe(Effect.provide(ActorSystemDefault)),
);

it.scopedLive("registers a nested child before parent spawn returns", () =>
Effect.gen(function* () {
const ChildState = State({ Active: {} });
const ChildEvent = Event({ Stop: {} });
const childMachine = Machine.make({
state: ChildState,
event: ChildEvent,
initial: ChildState.Active,
});
const parentMachine = Machine.make({
state: TestState,
event: TestEvent,
initial: TestState.Idle,
}).spawn(TestState.Idle, ({ self }) =>
self.spawn("nested-child", childMachine).pipe(Effect.asVoid, Effect.orDie),
);
const system = yield* ActorSystemService;

yield* system.spawn("nested-parent", parentMachine);

expect((yield* system.get("nested-child"))._tag).toBe("Some");
}).pipe(Effect.provide(ActorSystemDefault)),
);

it.scopedLive("stops actors properly", () =>
Effect.gen(function* () {
const machine = Machine.make({
Expand Down
Loading