Skip to content

Instantly share code, notes, and snippets.

@octosteve
Created June 20, 2019 14:13
Show Gist options
  • Save octosteve/6e8303ca2c2de6ea1ce9b0c30fdb9d17 to your computer and use it in GitHub Desktop.
Save octosteve/6e8303ca2c2de6ea1ce9b0c30fdb9d17 to your computer and use it in GitHub Desktop.
Separate state
defmodule Reducer do
use GenServer
def start_link(state_pid, options \\ []) do
GenServer.start_link(__MODULE__, state_pid, options)
end
def init(state_pid) do
{:ok, %{state_pid: state_pid}}
end
def run(callback) do
GenServer.cast(__MODULE__, {:run, callback})
end
def get_state do
GenServer.call(__MODULE__, :get_state)
end
def handle_cast({:run, callback}, state = %{state_pid: state_pid}) do
Agent.update(state_pid, callback)
{:noreply, state}
end
def handle_call(:get_state, _from, state = %{state_pid: state_pid}) do
{:reply, Agent.get(state_pid, &(&1)), state}
end
end
{:ok, state} = Agent.start_link(fn -> 0 end)
Reducer.start_link(state, name: Reducer)
Reducer.run(fn (num) -> num + 1 end)
Reducer.get_state
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment