Search code examples
elixirphoenix-frameworkgen-server

Storing pid of GenServer for future use


I need to start the GenServer at the time of Application start, however its PID will be required to call and cast Genserver. How will i obtain that in the rest of the application for future uses.


Solution

  • If GenServer will die and will be re-started by a supervisor it will receive new pid and your "stored" one will not be valid anymore - you will not be able to access your GenServer. This is why you should use name here:

    {:ok, _} = GenServer.start_link(MyApp, [:hello], name: :your_genserver_name)

    Then the call / cast would look like:

      def get_state do
        GenServer.call(:your_genserver_name, {:get_state})
      end
    

    Please refer this part of the docs for more details.