phoenix_playground icon indicating copy to clipboard operation
phoenix_playground copied to clipboard

Suggestions restarting the playground with new views in Livebook?

Open jakeprem opened this issue 9 months ago • 0 comments

Problem

I want to create a Livebook demonstrating a sequence of concepts, each one with its own LiveView. So a user/reader of the Livebook could run one example after the other.

By default PhoenixPlayground.start/1 just returns the PID, and I don't see a way to "update" the running Playground with new options. I'd like to avoid complicating my Livebook with a bunch of code to manage the PID.

Question

Does anyone already have a pattern or solution to this kind of thing?

I have a solution that will work for me but wasn't sure if there's a simpler option, or something we can incorporate into :phoenix_playground directly. If not I'm happy to keep using my own wrapper module.

Proposed Solution

  • Add PhoenixPlayground.stop() to stop the currently running playground.
  • Maybe add PhoenixPlayground.restart(opts) that will call PhoenixPlayground.stop() before calling start with the new opts? Or that calls stop after validating the opts for the new playground?

Implemented as a wrapper

defmodule PlaygroundManager do
  @moduledoc """
  A wrapper around PhoenixPlayground that makes it more LiveBook friendly.
  """

  def start(opts) do
    stop()

    PhoenixPlayground.start(opts)
  end

  def stop do
    case Supervisor.which_children(PhoenixPlayground.Application) do
      [{PhoenixPlayground, pid, _, _} | _] when is_pid(pid) ->
        Supervisor.terminate_child(PhoenixPlayground.Application, PhoenixPlayground)
        Supervisor.delete_child(PhoenixPlayground.Application, PhoenixPlayground)
        :ok
      _ -> {:error, :not_running}
    end
  end
end

Which can be used like:

defmodule FirstExampleLive do
 ...
end

PlaygroundManager.start(live: FirstExampleLive)

# second example block
defmodule SecondExampleLive do
...
end

PlaygroundManager.start(live: SecondExampleLive)

jakeprem avatar Feb 23 '25 22:02 jakeprem