Skip to content

Instantly share code, notes, and snippets.

@thejohncotton
Last active October 7, 2022 14:09
Show Gist options
  • Save thejohncotton/eb99b32e970540ed9eaf40c2dce8e622 to your computer and use it in GitHub Desktop.
Save thejohncotton/eb99b32e970540ed9eaf40c2dce8e622 to your computer and use it in GitHub Desktop.
Processes Livebook

OTP exercises

Mix.install([{:httpoison, "~> 1.8.2"}, {:jason, "~> 1.4.0"}, {:kino, "~> 0.7.0"}])
import IEx.Helpers
IEx.Helpers

Section

defmodule WeatherWorker do
  def get_weather(city) do
    :timer.sleep(:rand.uniform(500))

    # {:ok, response} = HTTPoison.get "http://api.openweathermap.org/data/2.5/weather?q=#{city}&APPID="
    # parsed_response = Jason.decode!(response.body)
    collector_pid = Process.whereis(:collector)
    weathers = ["sunny", "cloudy", "hot", "cold", "meh"]
    # weather = parsed_response["weather"] |> List.first
    send(collector_pid, {city, Enum.random(weathers)})
  end
end

defmodule Loopy do
  def loop do
    receive do
      {:hi, sender} ->
        send(sender, "Hi back!")

      anything_else ->
        IO.puts("I got: #{anything_else}")
    end

    loop()
  end
end

defmodule Simple do
  def puts_hello do
    IO.puts("hello")
  end
end

defmodule Collector do
  def run(state \\ []) do
    state =
      receive do
        :clear ->
          []

        {:report, sender} ->
          send(sender, state)
          state

        {city, condition} ->
          [{city, condition} | state]
      end

    run(state)
  end
end
{:module, Collector, <<70, 79, 82, 49, 0, 0, 7, ...>>, {:run, 1}}
looper = spawn(Loopy, :loop, [])
#PID<0.577.0>
simple = spawn(Simple, :puts_hello, [])
#PID<0.581.0>
hello
Process.alive?(simple)
false
Process.send(looper, "Hello World", [])
:ok
Process.alive?(looper)
true
Process.
defmodule ChrisProcess do
  def run(state \\ []) do
    receive do
      :greeting ->
        []

      {:greetings, sender} ->
        send(sender, "Hey Nice to hear from you")
        state
        run(state)

      "Hi" ->
        IO.puts("Hello you")
        run(state)

      number when is_integer(number) ->
        IO.puts("Oh you like numbers")
        run(state)

      :shh ->
        "bye"
    end
  end
end

chris = spawn(ChrisProcess, :run, [])
warning: variable state in code block has no effect as it is never returned (remove the variable or assign it to _ to avoid warnings)
  #cell:8: ChrisProcess.run/1

#PID<0.690.0>

                                    Process                                     

Conveniences for working with processes and the process dictionary.

Besides the functions available in this module, the Kernel module exposes and
auto-imports some basic functionality related to processes available through
the following functions:

  • Kernel.spawn/1 and Kernel.spawn/3
  • Kernel.spawn_link/1 and Kernel.spawn_link/3
  • Kernel.spawn_monitor/1 and Kernel.spawn_monitor/3
  • Kernel.self/0
  • Kernel.send/2

While this module provides low-level conveniences to work with processes,
developers typically use abstractions such as Agent, GenServer, Registry,
Supervisor and Task for building their systems and resort to this module for
gathering information, trapping exits, links and monitoring.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment