Genserver
From ElixirBlocks
mix new App --sup
app/lib/app.ex
defmodule App.Service do
use GenServer
def start_link(state) do
GenServer.start_link(__MODULE__, state, name: __MODULE__)
end
def init(state) do
{:ok, state}
end
def get_state(pid) do
GenServer.call(pid, :get_state)
end
def set_state(pid,state) do
GenServer.call(pid, {:set_state, state})
end
def handle_call(:get_state, _from, state) do
{:reply, state, state}
end
def handle_call({:set_state, new_state}, _from, state)do
{:reply,state,[new_state | state]}
end
end
defmodule App.Supervisor do
use Supervisor
def start do
Supervisor.start_link(__MODULE__, [])
end
def init(_) do
children = [
{App.Service,[]}
]
Supervisor.init(children, strategy: :one_for_one)
end
end
# App.Supervisor.start() # # IO.inspect x # pid = Process.whereis(App.Service) # # The follwing is nil # IO.inspect pid # Process.exit(pid, :kill) # IO.inspect "______________" # pid = Process.whereis(App.Service) # # IO.inspect "_____" # IO.inspect Process.whereis(App.Service) # App.Service.get_state(pid) # App.Service.set_state(pid, "we are the world") # App.Service.set_state(pid, "hurrrray") # IO.inspect App.Service.get_state(pid)
mix.exs
defmodule App.MixProject do
use Mix.Project
def project do
[
app: :app,
version: "0.1.0",
elixir: "~> 1.14",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger],
mod: {App.Application, []}
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
# {:dep_from_hexpm, "~> 0.3.0"},
# {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}
]
end
end
application.exs
defmodule App.Application do
# See https://hexdocs.pm/elixir/Application.html
# for more information on OTP Applications
@moduledoc false
use Application
@impl true
def start(_type, _args) do
children = [
# Starts a worker by calling: App.Worker.start_link(arg)
{App.Service, []}
]
opts = [strategy: :one_for_one, name: App.Supervisor]
Supervisor.start_link(children, opts)
end
end