From 59f7237816337ea4169cf5601c07077290c5c0be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonatan=20K=C5=82osko?= Date: Thu, 19 Sep 2024 18:59:18 +0700 Subject: [PATCH] Call off start_child when the group leader terminates --- lib/kino/terminator.ex | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/lib/kino/terminator.ex b/lib/kino/terminator.ex index e1ddaa8c..dc467ae6 100644 --- a/lib/kino/terminator.ex +++ b/lib/kino/terminator.ex @@ -30,8 +30,17 @@ defmodule Kino.Terminator do end if pid do - Kino.Bridge.reference_object(pid, parent) - Kino.Bridge.monitor_object(pid, cross_node_name(), {:terminate, pid}, ack?: true) + terminator = cross_node_name() + + with :ok <- Kino.Bridge.reference_object(pid, parent), + :ok <- Kino.Bridge.monitor_object(pid, terminator, {:terminate, pid}, ack?: true) do + :ok + else + # If we fail to reference the object, it means the group + # leader terminated, so we immediately terminate the started + # process + _ -> send(terminator, {:terminate, pid}) + end end resp @@ -75,6 +84,11 @@ defmodule Kino.Terminator do {:noreply, Map.delete(state, pid)} end + def handle_info({:terminate, pid}, state) do + DynamicSupervisor.terminate_child(Kino.DynamicSupervisor, pid) + {:noreply, Map.delete(state, pid)} + end + @impl true def handle_info({:DOWN, _, _, pid, reason}, state) do {parent, state} = Map.pop(state, pid)