water
How to only have [0,1]] Genserver for liveview
The genserver is only needed when a specific page is opened, and shouldn’t exist when none is on that page.
But adding it to application.ex makes it start even if none is on the page.
children = [
# ...
{MyApp.MyGenserver, [etc_config]}
MyApp.Endpoint
]
opts = [strategy: :one_for_one, name: MyApp.Supervisor]
Supervisor.start_link(children, opts)
When I place the call in the Liveview it launches an instance for everyone that is opening the page. And closes one after a page is closed.
def mount(_params, _session, socket) do
if connected?(socket) do
Supervisor.start_link(
[
{MyApp.MyGenserver,
[
host: @ip,
port: @port
]}
],
strategy: :one_for_one
)
end
{ :ok, socket }
end
I’m not sure what to try next. Could you point me in the right direction?
I know the following things exist, but not sure if they go in the right direction:
DynamicSupervisor.start_child/2Register
Marked As Solved
Also Liked
windexoriginal
What you want is start_child/2 and which_children/1. Provide a name for your applications supervisor (a module name style atom is conventional e.g. MyApp.Supervisor) and then when your liveview starts check if there is an existing child process using which_children/1 and start one under your application if none is found using start_child/2 using the name of your application supervisor.
But, I think you need a very good reason not to just go with your first solution and have the genserver start with your application.
derek-zhou
Yes, you need both the DynamicSupervisor and the Register. Do a Register.lookup/2 first, if none found start the genserver with DynamicSupervisor.start_child/2. Your genserver should auto-terminate if it is idle for some time. This system is not strictly 0 or 1 genserver at all time; there could be more than 1 genserver due to race condition. However, it should heal itself if that happened.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









