Last active
September 8, 2025 01:22
-
-
Save chiroptical/90dec30000cd6a268be8256aefe93ceb to your computer and use it in GitHub Desktop.
Sending messages to supervised children
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import gleam/erlang/process.{type Subject} | |
import gleam/otp/actor | |
import gleam/otp/static_supervisor.{type Supervisor} as supervisor | |
import gleam/otp/supervision | |
pub fn handle_message(state: Int, message: Message) -> actor.Next(Int, Message) { | |
case message { | |
Add(i) -> { | |
let state = state + i | |
actor.continue(state) | |
} | |
Get(reply) -> { | |
actor.send(reply, state) | |
actor.continue(state) | |
} | |
} | |
} | |
pub type Message { | |
Add(Int) | |
Get(Subject(Int)) | |
} | |
pub fn message_actor(parent_subject: Subject(Subject(Message))) { | |
actor.new_with_initialiser(1000, fn(_) { | |
let actor_subject: Subject(Message) = process.new_subject() | |
process.send(parent_subject, actor_subject) | |
let selector = | |
process.new_selector() | |
|> process.select(actor_subject) | |
Ok( | |
actor.initialised(0) | |
|> actor.selecting(selector), | |
) | |
}) | |
|> actor.on_message(handle_message) | |
|> actor.start | |
} | |
pub fn app_supervisor( | |
parent_subject: Subject(Subject(Message)), | |
) -> actor.StartResult(Supervisor) { | |
supervisor.new(supervisor.OneForOne) | |
|> supervisor.add( | |
supervision.worker(fn() { message_actor(parent_subject) }), | |
) | |
|> supervisor.start | |
} | |
pub fn main() { | |
let parent_subject: Subject(Subject(Message)) = process.new_subject() | |
let assert Ok(_actor) = app_supervisor(parent_subject) | |
let assert Ok(actor_subject) = process.receive(parent_subject, 1000) | |
actor.send(actor_subject, Add(5)) | |
actor.send(actor_subject, Add(3)) | |
assert actor.call(actor_subject, waiting: 10, sending: Get) == 8 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment