Terminated message when another actor stops. Use it to clean up references, fail
over, or react to actor lifecycle. The watched actor may live on another node: Watch on a remote PID registers the
watch there, and the Terminated message crosses the network.
API
- pid.Watch: Register to receive
Terminatedwhencidstops. - pid.UnWatch: Cancel the watch for
cid. - ctx.Watch:
ctx.Self().Watch(cid). - ctx.UnWatch:
ctx.Self().UnWatch(cid).
Watch and UnWatch are on *PID and ReceiveContext. Use ctx.Watch(pid) from inside Receive to watch another
actor.
Terminated message
When a watched actor stops, the watcher receives:Terminated message
Receive:
Terminated message
Terminatedis sent after the stopped actor’sPostStophas returned, and after its name is free, so a watcher may spawn the same name again as soon as it receives the message.- It is a control message: in the watcher it is handled ahead of the user messages still queued, and a watcher that is suspended at that moment still receives it.
- A restart is not a death: restarting a watched actor sends no
Terminated, and the watch stays in place. - Watching an actor that has already stopped registers nothing, and no
Terminatedever comes. - A parent watches each of its children automatically.
When to use
- Dependencies: Watch a child or peer; when it stops, recreate or fail over.
- Resource cleanup: Release references to the stopped actor.
- Supervision: Custom logic when a watched actor dies.
Automatic unwatch
When an actor stops, the system automatically callsUnWatch on all actors it was watching. Watchers do not need to
call UnWatch when they receive Terminated: the watch is already cancelled. Call UnWatch only when you want to stop
watching before the target terminates.
Example
Example