Book Image

Elixir Cookbook

By : Paulo Pereira
Book Image

Elixir Cookbook

By: Paulo Pereira

Overview of this book

Table of Contents (16 chapters)
Elixir Cookbook
About the Author
About the Reviewers

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)}

  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, _caller} ->
        IO.puts "Current status: #{pings} pings, #{pongs} pongs and #{unknown} unknown messages."

      {_, caller} ->