Popularity
9.0
Growing
Activity
7.8
-
346
98
35

Programming language: Elixir
License: GNU General Public License v3.0 only

phoenix-liveview-counter-tutorial alternatives and similar packages

Based on the "Examples and funny stuff" category.
Alternatively, view phoenix-liveview-counter-tutorial alternatives based on common mentions on social networks and blogs.

Do you think we are missing an alternative of phoenix-liveview-counter-tutorial or a related project?

Add another 'Examples and funny stuff' Package

README

Phoenix LiveView Counter Tutorial

GitHub Workflow Status codecov.io Hex.pm contributions welcome HitCount

Build your first App using Phoenix LiveView and understand all the concepts in 20 minutes or less!

Why? ๐Ÿคท

There are several example apps around the Internet using Phoenix LiveView but none include step-by-step instructions a complete beginner can follow. This is the complete beginner's tutorial we wish we had when learning LiveView and the one you have been searching for! ๐ŸŽ‰

What? ๐Ÿ’ญ

A complete beginners tutorial for building the most basic possible Phoenix LiveView App with no prior experience necessary.

LiveView?

Phoenix LiveView allows you to build rich interactive web apps with realtime reactive UI (no page refresh when data updates) without writing JavaScript! This enables building incredible user experiences with considerably less code.

LiveView pages load instantly because they are rendered on the Server and they require far less bandwidth than a similar React, Vue.js, Angular, etc. because only the bare minimum is loaded on the client for the page to work.

For a sneak peak of what is possible to build with LiveView, watch @chrismccord's LiveBeats intro:

https://user-images.githubusercontent.com/576796/162234098-31b580fe-e424-47e6-b01d-cd2cfcf823a9.mp4

Tip: Enable the sound. It's a collaborative music listening experience. ๐ŸŽถ

See: https://github.com/phoenixframework/phoenix_live_view

Who? ๐Ÿ‘ค

This tutorial is aimed at people who have never built anything in Phoenix or LiveView. You can speed-run it in 10 minutes if you're already familiar with Phoenix or Rails.

If you get stuck at any point while following the tutorial or you have any feedback/questions, please open an issue on GitHub!

If you don't have a lot of time or bandwidth to watch videos, this tutorial will be the fastest way to learn LiveView.

Prerequisites: What you Need Before You Start ๐Ÿ“

Before you start working through the tutorial, you will need:

a. Elixir installed on your computer. See: learn-elixir#installation

When you run the command:

elixir -v

You should expect to see output similar to the following:

Elixir 1.13.4 (compiled with Erlang/OTP 24)

This informs us we are using Elixir version 1.13.4 which is the latest version at the time of writing.

b. Phoenix installed on your computer. see: hexdocs.pm/phoenix/installation

If you run the following command in your terminal:

mix phx.new -v

You should see something similar to the following:

Phoenix installer v1.6.9

If you have an earlier version, definitely upgrade to get the latest features! If you have a later version of Phoenix, and you get stuck at any point, please open an issue on GitHub! We are here to help!

c. Basic familiarity with Elixir syntax is recommended but not essential; If you know any programming language, you can pick it up as you go and ask questions if you get stuck! See: https://github.com/dwyl/learn-elixir

How? ๐Ÿ’ป

This tutorial takes you through all the steps to build and test a counter in Phoenix LiveView. We always "begin with the end in mind" so we recommend running the finished app on your machine before writing any code.

๐Ÿ’ก You can also try the version deployed to Heroku: https://live-view-counter.herokuapp.com

Step 0: Run the Finished Counter App on your localhost ๐Ÿƒโ€

Before you attempt to build the counter, we suggest that you clone and run the complete app on your localhost. That way you know it's working without much effort/time expended.

Clone the Repository

On your localhost, run the following command to clone the repo and change into the directory:

git clone https://github.com/dwyl/phoenix-liveview-counter-tutorial.git
cd phoenix-liveview-counter-tutorial

Download the Dependencies

Install the dependencies by running the command:

mix setup

It will take a few seconds to download the dependencies depending on the speed of your internet connection; be patient. ๐Ÿ˜‰

Run the App

Start the Phoenix server by running the command:

mix phx.server

Now you can visit localhost:4000 in your web browser.

๐Ÿ’ก Open a second browser window (e.g. incognito mode), you will see the the counter updating in both places like magic!

You should expect to see:

phoenix-liveview-counter-start

With the finished version of the App running on your machine and a clear picture of where we are headed, it's time to build it!

Step 1: Create the App ๐Ÿ†•

In your terminal run the following mix command to generate the new Phoenix app:

mix phx.new live_view_counter --no-ecto

The --no-ecto flag tells mix phx.new to create an App without a Database. This keeps our counter as simple as possible. We can always add a Database later.

Note: Since Phoenix 1.6 the --live flag is no longer required when creating a LiveView app. LiveView is included by default in all new Phoenix Apps. Older tutorials may still include the flag, everything is much easier now.

When you see the following prompt:

Fetch and install dependencies? [Yn]

Type Y followed by the [Enter] key. That will download all the necessary dependencies.

Checkpoint 1: Run the Tests!

In your terminal, go into the newly created app folder using:

cd live_view_counter

And then run the following mix command:

mix test

You should see:

Compiling 14 files (.ex)
Generated live_view_counter app
...

Finished in 0.03 seconds (0.02s async, 0.01s sync)
3 tests, 0 failures

Tests all pass. This is expected with a new app. It's a good way to confirm everything is working.

Checkpoint 1b: Run the New Phoenix App!

Run the server by executing this command:

mix phx.server

Visit localhost:4000 in your web browser.

welcome-to-phoenix

Step 2: Create the counter.ex File

Create a new file with the path: lib/live_view_counter_web/live/counter.ex

And add the following code to it:

defmodule LiveViewCounterWeb.Counter do
  use Phoenix.LiveView

  def mount(_params, _session, socket) do
    {:ok, assign(socket, :val, 0)}
  end

  def handle_event("inc", _, socket) do
    {:noreply, update(socket, :val, &(&1 + 1))}
  end

  def handle_event("dec", _, socket) do
    {:noreply, update(socket, :val, &(&1 - 1))}
  end

  def render(assigns) do
    ~L"""
    <div>
      <h1>The count is: <%= @val %></h1>
      <button phx-click="dec">-</button>
      <button phx-click="inc">+</button>
    </div>
    """
  end
end

Explanation of the Code

The first line instructs Phoenix to use the Phoenix.LiveView behaviour. This loads just means that we will need to implement certain functions for our live view to work.

The first function is mount/3 which, as it's name suggests, mounts the module with the _params, _session and socket arguments:

def mount(_params, _session, socket) do
  {:ok, assign(socket, :val, 0) }
end

In our case we are ignoring the _params and _session, hence the underscore prepended to the parameters. If we were using sessions for user management, we would need to check the session variable, but in this simple counter example we just ignore it.

mount/3 returns a tuple: {:ok, assign(socket, :val, 0)} which uses the assign/3 function to assign the :val key a value of 0 on the socket. That just means the socket will now have a :val which is initialised to 0.

The second function is handle_event/3 which handles the incoming events received. In the case of the first declaration of handle_event("inc", _, socket) it pattern matches the string "inc" and increments the counter.

def handle_event("inc", _, socket) do
  {:noreply, update(socket, :val, &(&1 + 1))}
end

handle_event/3 ("inc") returns a tuple of: {:noreply, update(socket, :val, &(&1 + 1))} where the :noreply just means "do not send any further messages to the caller of this function". update(socket, :val, &(&1 + 1)) as it's name suggests, will update the value of :val on the socket to the &(&1 + 1) is a shorthand way of writing fn val -> val + 1 end. the &() is the same as fn ... end (where the ... is the function definition). If this inline anonymous function syntax is unfamiliar to you, please read: https://elixir-lang.org/crash-course.html#partials-and-function-captures-in-elixir

The third function is almost identical to the one above, the key difference is that it decrements the :val.

def handle_event("dec", _, socket) do
  {:noreply, update(socket, :val, &(&1 - 1))}
end

handle_event("dec", _, socket) pattern matches the "dec" String and decrements the counter using the &(&1 - 1) syntax.

In Elixir we can have multiple similar functions with the same function name but different matches on the arguments or different "arity" (number of arguments). For more detail on Functions in Elixir, see: https://elixirschool.com/en/lessons/basics/functions/#named-functions

Finally the forth function render/1 receives the assigns argument which contains the :val state and renders the template using the @val template variable.

The render/1 function renders the template included in the function. The ~L""" syntax just means "treat this multiline string as a LiveView template" The ~L sigil is a macro included when the use Phoenix.LiveView is invoked at the top of the file.

LiveView will invoke the mount/3 function and will pass the result of mount/3 to render/1 behind the scenes.

Each time an update happens (e.g: handle_event/3) the render/1 function will be executed and updated data (in our case the :val count) is sent to the client.

๐Ÿ At the end of Step 2 you should have a file similar to: lib/live_view_counter_web/live/counter.ex

Step 3: Create the live Route in router.ex

Now that we have created our Live handler function in Step 4, it's time to tell Phoenix how to invoke it.

Open the lib/live_view_counter_web/router.ex file and locate the block of code that starts with scope "/", LiveViewCounterWeb do:

scope "/", LiveViewCounterWeb do
  pipe_through :browser

  get "/", PageController, :index
end

Replace the line get "/", PageController, :index with live("/", Counter). So you end up with:

scope "/", LiveViewCounterWeb do
  pipe_through :browser

  live("/", Counter)
end

3.1 Update the Failing Test Assertion

Since we have replaced the get "/", PageController, :index route in router.ex in the previous step, the test in test/live_view_counter_web/controllers/page_controller_test.exs will now fail:

Compiling 1 file (.ex)
..

1) test GET / (LiveViewCounterWeb.PageControllerTest)
   test/live_view_counter_web/controllers/page_controller_test.exs:4
   Assertion with =~ failed
   code:  assert html_response(conn, 200) =~ "Welcome to Phoenix!"
   left:  "<html lang=\"en\"><head><meta charset=\"utf-8\"/><meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"/><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"/><meta charset=\"UTF-8\" content=\"IHQLHHISBjZlWTskHjAmHBETKCFnGWUloYSOGMkDRhaSvIBtkycvQNUF\" csrf-param=\"_csrf_token\" method-param=\"_method\" name=\"csrf-token\"/><title data-suffix=\" ยท Phoenix Framework\">LiveViewCounter ยท Phoenix Framework</title><link phx-track-static=\"phx-track-static\" rel=\"stylesheet\" href=\"/css/app.css\"/><script defer=\"defer\" phx-track-static=\"phx-track-static\" type=\"text/javascript\" src=\"/js/app.js\"></script></head><body><header><section class=\"container\"><nav role=\"navigation\"><ul><li><a href=\"https://hexdocs.pm/phoenix/overview.html\">Get Started</a></li><li><a href=\"/dashboard\">LiveDashboard</a></li></ul></nav><a href=\"https://phoenixframework.org/\" class=\"phx-logo\"><img src=\"/images/phoenix.png\" alt=\"Phoenix Framework Logo\"/></a></section></header><div data-phx-main=\"true\" data-phx-session=\"SFMyNTY" data-phx-view=\"Counter\" id=\"phx-FhQ9AJF6KACJPAEm\"><div><h1>The count is: 0</h1><button phx-click=\"dec\">-</button><button phx-click=\"inc\">+</button></div></div></body></html>"
   right: "Welcome to Phoenix!"
   stacktrace:
     test/live_view_counter_web/controllers/page_controller_test.exs:6: (test)


Finished in 0.1 seconds
3 tests, 1 failure

This just tells us that the test is looking for the string "Welcome to Phoenix!" in the page and did not find it.

To fix the broken test, open the test/live_view_counter_web/controllers/page_controller_test.exs file and locate the line:

assert html_response(conn, 200) =~ "Welcome to Phoenix!"

Update the string from "Welcome to Phoenix!" to something we know is present on the page, e.g: "The count is"

๐Ÿ The page_controller_test.exs.exs file should now look like this: test/live_view_counter_web/controllers/page_controller_test.exs#L6

Confirm the tests pass again by running:

mix test

You should see output similar to:

Generated live_view_counter app
...

Finished in 0.05 seconds
3 tests, 0 failures

Checkpoint: Run Counter App!

Now that all the code for the counter.ex is written, run the Phoenix app with the following command:

mix phx.server

Vist localhost:4000 in your web browser.

You should expect to see a fully functioning LiveView counter:

phoenix-liveview-counter-single-windowl

Recap: Working Counter Without a JavaScript Framework

Once the initial installation and configuration of LiveView was complete, the creation of the actual counter was remarkably simple. We created a single new file lib/live_view_counter_web/live/counter.ex that contains all the code required to initialise, render and update the counter. Then we set the live("/", Counter) route to invoke the Counter module in router.ex.

In total our counter App is 25 lines of code.

One important thing to note is that the counter only maintains state for a single web browser. Try opening a second browser window (e.g: in "incognito mode") and notice how the counter only updates in one window at a time:

phoenix-liveview-counter-two-windows-independent-count

If we want to share the counter state between multiple clients, we need to add a bit more code.

Step 4: Share State Between Clients!

One of the biggest selling points of using Phoenix to build web apps is the built-in support for WebSockets in the form of "channels". Phoenix Channels allow us to effortlessly sync data between clients and servers with minimal overhead.

We can share the counter state between multiple clients by updating the counter.ex file with the following code:

defmodule LiveViewCounterWeb.Counter do
  use Phoenix.LiveView

  @topic "live"

  def mount(_session, _params, socket) do
    LiveViewCounterWeb.Endpoint.subscribe(@topic) # subscribe to the channel
    {:ok, assign(socket, :val, 0)}
  end

  def handle_event("inc", _value, socket) do
    new_state = update(socket, :val, &(&1 + 1))
    LiveViewCounterWeb.Endpoint.broadcast_from(self(), @topic, "inc", new_state.assigns)
    {:noreply, new_state}
  end

  def handle_event("dec", _, socket) do
    new_state = update(socket, :val, &(&1 - 1))
    LiveViewCounterWeb.Endpoint.broadcast_from(self(), @topic, "dec", new_state.assigns)
    {:noreply, new_state}
  end

  def handle_info(msg, socket) do
    {:noreply, assign(socket, val: msg.payload.val)}
  end

  def render(assigns) do
    ~L"""
    <div>
      <h1>The count is: <%= @val %></h1>
      <button phx-click="dec">-</button>
      <button phx-click="inc">+</button>
    </div>
    """
  end
end

Code Explanation

The first change is on Line 4 @topic "live" defines a module attribute (think of it as a global constant), that lets us to reference @topic anywhere in the file.

The second change is on Line 7 where the mount/3 function now creates a subscription to the topic:

LiveViewCounterWeb.Endpoint.subscribe(@topic) # subscribe to the channel topic

Each client connected to the App subscribes to the @topic so when the count is updated on any of the clients, all the other clients see the same value. This uses Phoenix's built-in channels (WebSocket) system.

Next we update the first handle_event/3 function which handles the "inc" event:

def handle_event("inc", _msg, socket) do
  new_state = update(socket, :val, &(&1 + 1))
  LiveViewCounterWeb.Endpoint.broadcast_from(self(), @topic, "inc", new_state.assigns)
  {:noreply, new_state}
end

Assign the result of the update invocation to new_state so that we can use it on the next two lines. Invoking LiveViewCounterWeb.Endpoint.broadcast_from sends a message from the current process self() on the @topic, the key is "inc" and the value is the new_state.assigns Map.

In case you are curious (like we are), new_state is an instance of the Phoenix.LiveView.Socket socket:

#Phoenix.LiveView.Socket<
  assigns: %{
    flash: %{},
    live_view_action: nil,
    live_view_module: LiveViewCounterWeb.Counter,
    val: 1
  },
  changed: %{val: true},
  endpoint: LiveViewCounterWeb.Endpoint,
  id: "phx-Ffq41_T8jTC_3gED",
  parent_pid: nil,
  view: LiveViewCounterWeb.Counter,
  ...
}

The new_state.assigns is a Map that includes the key val where the value is 1 (after we clicked on the increment button).

The fourth update is to the "dec" version of handle_event/3

def handle_event("dec", _msg, socket) do
  new_state = update(socket, :val, &(&1 - 1))
  LiveViewCounterWeb.Endpoint.broadcast_from(self(), @topic, "dec", new_state.assigns)
  {:noreply, new_state}
end

The only difference from the "inc" version is the &(&1 - 1) and "dec" in the broadcast_from.

The final change is the implementation of the handle_info/2 function:

def handle_info(msg, socket) do
  {:noreply, assign(socket, val: msg.payload.val)}
end

handle_info/2 handles Elixir process messages where msg is the received message and socket is the Phoenix.Socket. The line {:noreply, assign(socket, val: msg.payload.val)} just means "don't send this message to the socket again" (which would cause a recursive loop of updates).

๐Ÿ At the end of Step 6 the file looks like: lib/live_view_counter_web/live/counter.ex

Checkpoint: Run It!

Now that counter.ex has been updated to broadcast the count to all connected clients, let's run the app in a few web browsers to show it in action!

In your terminal, run:

mix phx.server

Open localhost:4000 in as many web browsers as you have and test the increment/decrement buttons!

You should see the count increasing/decreasing in all browsers simultaneously!

phoenix-liveview-counter-four-windows

Congratulations! ๐ŸŽ‰

You just built a real-time counter that seamlessly updates all connected clients using Phoenix LiveView in less than 40 lines of code!

<!-- uncomment this if you want to help get it working.

Step 7: Use a LiveView Template (Optional)

At present the render/1 function in counter.ex has an inline template:

def render(assigns) do
  ~L"""
  <div>
    <h1>The count is: <%= @val %></h1>
    <button phx-click="dec">-</button>
    <button phx-click="inc">+</button>
  </div>
  """

This is fine when the template is small like in this counter, but it's a good idea to split the template into a separate file to make it easier to read and maintain.

Create a new file with the path: lib/live_view_counter_web/templates/counter.html.leex

and add the following code to it:

<div>
  <h1>The count is: <%= @val %></h1>
  <button phx-click="dec">-</button>
  <button phx-click="inc">+</button>
</div>

๐Ÿ Your counter.html.leex should look like this: lib/live_view_counter_web/templates/counter.html.leex

That template is identical to the one we had in the render/1 function. That's the point; we just want it in a separate file.

Now open the counter.ex file and locate the render/1 function. Update the code to:

def render(assigns) do
  LiveViewCounterWeb.PageView.render("counter.html", assigns)
end

๐Ÿ At the end of Step 7 your counter.ex file should resemble: lib/live_view_counter_web/live/counter.ex

Re-run your app using mix phx.server and confirm everything still works:

phoenix-liveview-counter-42

Done!

-->

That's it for this tutorial. We hope you enjoyed learning with us! If you found this useful, please โญ๏ธ and share the GitHub repo so we know you like it!

What's Next?

If you've enjoyed this basic counter tutorial and want something a bit more advanced, checkout our LiveView Chat Tutorial: github.com/dwyl/phoenix-liveview-chat-example

Feedback

Several people in the Elixir / Phoenix community have found this tutorial helpful when starting to use LiveView, e.g: Kurt Mackey @mrkurt twitter.com/mrkurt/status/1362940036795219973

mrkurt-liveview-tweet

He deployed the counter app to a 17 region cluster using fly.io: https://liveview-counter.fly.dev

liveview-counter-cluster

Code: https://github.com/fly-apps/phoenix-liveview-cluster/blob/master/lib/live_view_counter_web/live/counter.ex

Your feedback is always very much welcome! ๐Ÿ™

Future Steps

Moving state out of the LiveViews

With this implementation you may have noticed that when we open a new browser window the count is always zero. As soon as we click plus or minus it adjusts and all the views get back in line. This is because the state is replicated across LiveView instances and coordinated via pub-sub. If the state was big and complicated this would get wasteful in resources and hard to manage.

Generally it is good practice to identify shared state and to manage that in a single location.

The Elixir way of managing state is the GenServer, using PubSub to update the LiveViews about changes. This allows the LiveViews to focus on user specific state, separating concerns; making the application both more efficient (hopefully) and easier to reason about and debug.

We are now going to start making use of the lib/live_view_counter directory! The Phoenix docs says that this holds "all of your business domain". For us this is the current count, along with the incr and decr methods.

Create a file with the path lib/live_view_counter/counter.ex and add the following:

defmodule LiveViewCounter.Count do
  use GenServer

  alias Phoenix.PubSub

  @name :count_server

  @start_value 0

  # -------  External API (runs in client process) -------

  def topic do
    "count"
  end

  def start_link(_opts) do
    GenServer.start_link(__MODULE__, @start_value, name: @name)
  end

  def incr() do
    GenServer.call @name, :incr
  end

  def decr() do
    GenServer.call @name, :decr
  end

  def current() do
    GenServer.call @name, :current
  end

  def init(start_count) do
    {:ok, start_count}
  end

  # -------  Implementation  (Runs in GenServer process) -------

  def handle_call(:current, _from, count) do
     {:reply, count, count}
  end

  def handle_call(:incr, _from, count) do
    make_change(count, +1)
  end

  def handle_call(:decr, _from, count) do
    make_change(count, -1)
  end

  defp make_change(count, change) do
    new_count = count + change
    PubSub.broadcast(LiveViewCounter.PubSub, topic(), {:count, new_count})
    {:reply, new_count, new_count}
  end
end

The GenServer runs in its own process. Other parts of the application invoke the API in their own process, these calls are forwarded to the handle_call functions in the GenServer process where they are processed serially.

We have also moved the PubSub publication here as well.

We are also going to need to tell the Application that it now has some business logic; we do this in the start/2 function in the lib/live_view_counter/application.ex file.

  def start(_type, _args) do
    children = [
      # Start the App State
+     LiveViewCounter.Count,
      # Start the Telemetry supervisor
      LiveViewCounterWeb.Telemetry,
      # Start the PubSub system
      {Phoenix.PubSub, name: LiveViewCounter.PubSub},
      # Start the Endpoint (http/https)
      LiveViewCounterWeb.Endpoint
      # Start a worker by calling: LiveViewCounter.Worker.start_link(arg)
      # {LiveViewCounter.Worker, arg}
    ]

    # See https://hexdocs.pm/elixir/Supervisor.html
    # for other strategies and supported options
    opts = [strategy: :one_for_one, name: LiveViewCounter.Supervisor]
    Supervisor.start_link(children, opts)
  end
...

Finally, we are going to have to make some changes to the LiveView itself, it now has less to do!

defmodule LiveViewCounterWeb.Counter do
  use Phoenix.LiveView
  alias LiveViewCounter.Count
  alias Phoenix.PubSub

  @topic Count.topic

  def mount(_params, _session, socket) do
    PubSub.subscribe(LiveViewCounter.PubSub, @topic)

    {:ok, assign(socket, val: Count.current()) }
  end

  def handle_event("inc", _, socket) do
    {:noreply, assign(socket, :val, Count.incr())}
  end

  def handle_event("dec", _, socket) do
    {:noreply, assign(socket, :val, Count.decr())}
  end

  def handle_info({:count, count}, socket) do
    {:noreply, assign(socket, val: count)}
  end

  def render(assigns) do
    ~L"""
    <div>
      <h1>The count is: <%= @val %></h1>
      <button phx-click="dec">-</button>
      <button phx-click="inc">+</button>
    </div>
    """
  end
end

What is happening now is that the initial state is being retrieved from the shared Application GenServer process and the updates are being forwarded there via its API. Finally, the Gen Server Handlers publish the new state to all the active LiveViews.

How many people are using the Counter?

Phoenix has a very cool feature called Presence to track how many people are using our system. (It does a lot more than count users, but this is a counting app so...)

First of all we need to tell the Application we are going to use Presence. For this we need to create a lib/live_view_counter/presence.ex file like this:

defmodule LiveViewCounter.Presence do
  use Phoenix.Presence,
    otp_app: :live_view_counter,
    pubsub_server: LiveViewCounter.PubSub
end

and tell the application about it in the lib/live_view_counter/application.ex file (add it just below the PubSub config):

  def start(_type, _args) do
    children = [
      # Start the App State
      LiveViewCounter.Count,
      # Start the Telemetry supervisor
      LiveViewCounterWeb.Telemetry,
      # Start the PubSub system
      {Phoenix.PubSub, name: LiveViewCounter.PubSub},
+     LiveViewCounter.Presence,
      # Start the Endpoint (http/https)
      LiveViewCounterWeb.Endpoint
      # Start a worker by calling: LiveViewCounter.Worker.start_link(arg)
      # {LiveViewCounter.Worker, arg}
    ]

    # See https://hexdocs.pm/elixir/Supervisor.html
    # for other strategies and supported options
    opts = [strategy: :one_for_one, name: LiveViewCounter.Supervisor]
    Supervisor.start_link(children, opts)
  end

The application doesn't need to know any more about the user count (it might, but not here) so the rest of the code goes into lib/live_view_counter_web/live/counter.ex.

  1. We subscribe to and participate in the Presence system (we do that in mount)
  2. We handle Presence updates and use the current count, adding joiners and subtracting leavers to calculate the current numbers 'present'. We do that in a pattern matched handle_info.
  3. We publish the additional data to the client in render
defmodule LiveViewCounterWeb.Counter do
  use Phoenix.LiveView
  alias LiveViewCounter.Count
  alias Phoenix.PubSub
+ alias LiveViewCounter.Presence

  @topic Count.topic
+ @presence_topic "presence"

  def mount(_params, _session, socket) do
    PubSub.subscribe(LiveViewCounter.PubSub, @topic)

+   Presence.track(self(), @presence_topic, socket.id, %{})
+   LiveViewCounterWeb.Endpoint.subscribe(@presence_topic)
+
+   initial_present =
+     Presence.list(@presence_topic)
+     |> map_size

+   {:ok, assign(socket, val: Count.current(), present: initial_present) }
-   {:ok, assign(socket, val: Count.current()) }
  end

  def handle_event("inc", _, socket) do
    {:noreply, assign(socket, :val, Count.incr())}
  end

  def handle_event("dec", _, socket) do
    {:noreply, assign(socket, :val, Count.decr())}
  end

  def handle_info({:count, count}, socket) do
    {:noreply, assign(socket, val: count)}
  end

+ def handle_info(
+       %{event: "presence_diff", payload: %{joins: joins, leaves: leaves}},
+       %{assigns: %{present: present}} = socket
+    ) do
+   new_present = present + map_size(joins) - map_size(leaves)
+
+   {:noreply, assign(socket, :present, new_present)}
+ end

  def render(assigns) do
    ~L"""
    <div>
      <h1>The count is: <%= @val %></h1>
      <button phx-click="dec">-</button>
      <button phx-click="inc">+</button>
+     <h1>Current users: <%= @present %></h1>
    </div>
    """
  end
end

Now, as you open and close your incognito windows you will get a count of how many are running.

Credits & Thanks! ๐Ÿ™Œ

Credit for inspiring this tutorial goes to Dennis Beatty @dnsbty for his superb post: https://dennisbeatty.com/2019/03/19/how-to-create-a-counter-with-phoenix-live-view.html and corresponding video: youtu.be/2bipVjOcvdI

dennisbeatty-counter-video

We recommend everyone learning Elixir subscribe to his YouTube channel and watch all his videos as they are a superb resource!

The 3 key differences between this tutorial and Dennis' original post are:

  1. Complete code commit (snapshot) at the end of each section (not just inline snippets of code). We feel that having the complete code speeds up learning significantly, especially if (when) we get stuck.
  2. Latest Phoenix, Elixir and LiveView versions. A few updates have been made to LiveView setup, these are reflected in our tutorial which uses the latest release.
  3. Broadcast updates to all connected clients. So when the counter is incremented/decremented in one client, all others see the update. This is the true power and "wow moment" of LiveView!

Phoenix LiveView for Web Developers Who Don't know Elixir

If you are new to LiveView (and have the bandwidth), we recommend watching James @knowthen Moore's intro to LiveView where he explains the concepts: youtu.be/U_Pe8Ru06fM

phoenix-liveview-intro-

Watching the video is not required; you will be able to follow the tutorial without it.

Chris McCord (creator of Phoenix and LiveView) has github.com/chrismccord/phoenix_live_view_example chris-phoenix-live-view-example-rainbow It's a great collection of examples for people who already understand LiveView. However we feel that it is not very beginner-friendly (at the time of writing). Only the default "start your Phoenix server" instructions are included, and the dependencies have diverged so the app does not compile/run for some people. We understand/love that Chris is focussed building Phoenix and LiveView so we decided to fill in the gaps and write this beginner-focussed tutorial.

If you haven't watched Chris' Keynote from ElixirConf EU 2019, we highly recommend watching it: youtu.be/8xJzHq8ru0M

chris-keynote-elixirconf-eu-2019

Also read the original announcement for LiveView to understand the hype! : https://dockyard.com/blog/2018/12/12/phoenix-liveview-interactive-real-time-apps-no-need-to-write-javascript

Sophie DeBenedetto's ElixirConf 2019 talk "Beyond LiveView: Building Real-Time features with Phoenix LiveView, PubSub, Presence and Channels (Hooks) is worth watching: youtu.be/AbNAuOQ8wBE

Sophie-DeBenedetto-elixir-conf-2019-talk

Related blog post: https://elixirschool.com/blog/live-view-live-component/