Starting dynamically children from a supervisor pattern

Hello,

I started, as an exercise, a little pet project to fetch tweets via twitter’s stream api using ExTwitter

You can see the supervisor here https://github.com/kpanic/tweetyodel/blob/master/lib/tweets_supervisor.ex
My aim would be to integrate it with phoenix channels, however I am using this code, which, seems to me not the most elegant:

  def join("tweets:" <> namespace, payload, socket) do
    unless is_pid(Tweetyodel.Worker.whereis(namespace)) do
      {:ok, _} = Tweetyodel.Worker.Supervisor.start_tweet(namespace)
    end
    if authorized?(payload) do
      {:ok, assign(socket, :namespace, namespace)}
    else
      {:error, %{reason: "unauthorized"}}
    end
  end

Which involves checking if the child is already started (via Tweetyodel.Worker.whereis(namespace))
I am wondering if there’s a different approach to handle this case or if I should just:

Tweetyodel.Worker.Supervisor.start_tweet(namespace)
even without pattern matching{:ok, _} so that I will ignore the :already_started match, which seems also not a good idea :wink:
Maybe a case statement?

Thanks in advance for the suggestions!

1 Like

I would do a case statement on both the :ok and :already_started responses. That way any error response will get propagated.

1 Like

Thanks @gregvaughn – makes sense!