O'Reilly logo

Elixir Cookbook by Paulo A Pereira

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Creating a stateful server process (messages with counters)

In this recipe, we will use the same concept used in the first recipe, but we will add a counter for each type of received message. We will introduce states!

Getting ready

To get started, let's create a module named messages_with_state.ex with the following code:

defmodule MessagesWithState do

  def start_link do
    {:ok, spawn_link(fn -> wait_for_messages(0,0,0) end)}
  end

  defp wait_for_messages(pings, pongs, unknown) do
    receive do
      {"ping", caller} ->
        send caller, "pong"
        IO.puts "Received #{pings + 1} ping messages!"
        wait_for_messages(pings + 1, pongs, unknown)

      {"pong", caller} ->
        send caller, "pong"
        IO.puts "Received #{pongs + 1} pong messages!"
        wait_for_messages(pings, pongs + 1, unknown) {:status, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required