I am getting data from an endpoint comming in a list , assume they are unique id's I try attempt to start a GenServer process for each of them but

def new(conn, %{"hashes" => [_ | _] = hashes}) do
  results = Enum.map(hashes, &call_hash/1)

  if Enum.all?(results, & &1 == :ok) do
    json(conn, %{status: "Ok"})
  else
    conn
    |> put_status(400)
    |> json(%{status: "Failed"})
  end
end

defp call_hash(conn,hash) do
  with {:ok, _} <- GenServer.start_link(TransactionSubscriptionHandler, %{hash: String.to_atom(hash)}, name: String.to_atom(hash))
     {:ok, %{status: 200}} <- BlockNative.subscribe_transaction(hash) do
     :ok
  else
     _ -> :error
  end
end

The big changes:

  • split “doing the thing” apart from “rendering the response”; call_hash could be moved out of the controller if desired, and doesn’t need to know anything about conn
  • use Enum.map instead of Enum.each. Each always returns just the atom :ok, and we care about the results here.