Skip to content

Instantly share code, notes, and snippets.

@TylerPachal
Last active January 30, 2019 16:33
Show Gist options
  • Save TylerPachal/f3d4b3d5467ee7a8702af40b15bd0368 to your computer and use it in GitHub Desktop.
Save TylerPachal/f3d4b3d5467ee7a8702af40b15bd0368 to your computer and use it in GitHub Desktop.
defmodule MyServer do
# ...
# Some sort of async operation that needs to be done on the data
def handle_cast({:increment, id}, state) do
Logger.info("#{state.type} - increment #{id}")
updated_data = Map.update(state.data, id, 1, fn v -> v + 1 end)
updated_state = Map.put(state, :data, updated_data)
{:noreply, updated_state}
end
# ...
end
# Our new process which continuously sends messages to the other process
defmodule Spammer do
use GenServer
def start_link([]) do
GenServer.start_link(__MODULE__, :ok)
end
def init(:ok) do
loop()
{:ok, :state}
end
def handle_info(:send_message, state) do
Enum.each([:users, :messages, :items], fn name ->
:ok = GenServer.cast(name, {:increment, "id"})
end)
loop()
{:noreply, state}
end
defp loop() do
self() |> send(:send_message)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment