Most tutorials on this seem outdated. I hunted thru the hexdocs on DynamicSupervisor and GenServer, but I find it all very confusing.
This example seems to work for me just fine, and was really helpful, but it doesn’t show how to kill my child process by name. How do I do that?
https://thoughtbot.com/blog/how-to-start-processes-with-dynamic-names-in-elixir
Your child in the supervisor iis just a GenServer (or something that builds upon it). So you can stop it just as you do with GenServer.
Via GenServer cheatsheet (https://elixir-lang.org/cheatsheets/gen-server.pdf), you need to add these two functions to it’s implementation
def stop(pid, reason \\ :normal, timeout \\ :infinity) do
GenServer.stop(pid, reason, timeout)
end
def terminate(reason, state) do
# perform cleanup
# result will not be used
end
And call it with reaason set to :normal so the process will not get restarted by DynamicSupervisor.
You can also add a stop API hook:
def stop(who), do: GenServer.call({:via, Registry..., :stop)
def handle_call(:stop, _, state) do
#pre-stop things
{:stop, :normal, reply, state}
end
Note that calling GenServer.stop will bypass this so you have options about where you want to put your stopping cleanup logic.
The cheatsheet is especially helpful.
https://elixir-lang.org/cheatsheets/gen-server.pdf
After solving the problem I asked about, I still had other issues to solve and this cheatsheet got me thru it. Many thanks.