Application with two instances of the same GenServer

I am having a simple Phoenix Liveview app.

The app should have two actors, let’s say Alice and Bob. Both should be instances of the same GenServer module, as they’re gonna receive events and obviously have the same functionalities.

Looking for a clean way to instantiate them both as children of the application’s supervisor… and make sure they’re easily accessible from live views.

Just start two named processes under your Supervisor.

As an aside, something I won’t get tired of repeating - Phoenix is not your application.

1 Like

You’ll need to use Supervisor — Elixir v1.12.3
For instance :

children =
      [Supervisor.child_spec(
          {MyModule, %{},
          id: :alice
        ),
    Supervisor.child_spec(
          {MyModule, %{},
          id: :bob
        )
 ] ++ children(target())
1 Like

Actually I’m not sure id option is required here, since the supervisor can handle this on it’s own, to address the genservers easily you need to give them global names using name registration:

children = [
  {MyGenserver, [], name: :bob},
  {MyGenserver, [], name: :alice}
]

So then you can easily call them using:

GenServer.call(:bob, :hello_bob)
GenServer.call(:alice, :hello_alice)
1 Like