Trigger (trigger v1.0.0) View Source

A simple way to sync between processes.

Link to this section Summary

Types

t()

A Trigger data type.

Functions

Sends a new event with arbitrary data to the receiver.

Sends a new event with arbitrary data to the receiver and waits for a reply.

Creates a new Trigger.

Sends a reply back to the process which sent the event.

Waits fot an event and sends a reply back right away.

Link to this section Types

Specs

t()

A Trigger data type.

Link to this section Functions

Link to this function

fire(trigger, data \\ nil)

View Source

Specs

fire(t(), term()) :: :ok

Sends a new event with arbitrary data to the receiver.

Examples

iex> trigger = Trigger.new()
%Trigger{...}
iex> Trigger.fire(trigger)
:ok
iex> Trigger.wait(trigger)
{#PID<0.257.0>, nil}
Link to this function

fire_wait(trigger, data \\ nil, timeout \\ :infinity)

View Source

Specs

fire_wait(t(), term(), timeout()) :: term() | no_return()

Sends a new event with arbitrary data to the receiver and waits for a reply.

Examples

iex> trigger = Trigger.new()
%Trigger{...}
iex> pid = spawn(fn ->
...>   "Hello, world" = Trigger.fire_wait(trigger, "world")
...> end)
#PID<0.262.0>
iex> {sender, name} = Trigger.wait(trigger)
{#PID<0.262.0>, "world"}
iex> Process.alive?(pid)
true
iex> Trigger.reply(trigger, sender, "Hello, #{name}")
:ok
iex> Process.alive?(pid)
false

Specs

new(options) :: t() when options: [{:receiver, Process.dest()}]

Creates a new Trigger.

Options

  • receiver - configure an event receiver, defaults to self()

Examples

iex> Trigger.new()
%Trigger{...}
Link to this function

reply(trigger, to, reply \\ nil)

View Source

Specs

reply(t(), pid(), term()) :: :ok

Sends a reply back to the process which sent the event.

Link to this function

wait(trigger, timeout \\ :infinity)

View Source

Specs

wait(t(), timeout()) :: {pid(), term()} | no_return()

Waits for an event.

For examples see fire/2 or fire_wait/3.

Link to this function

wait_reply(trigger, data \\ nil, timeout \\ :infinity)

View Source

Specs

wait_reply(t(), term(), timeout()) :: term() | no_return()

Waits fot an event and sends a reply back right away.

This is useful to have a two-way sync between processes, so event-sender knows that the receiver has got the event.

Examples

iex> trigger = Trigger.new()
%Trigger{...}
iex> test = fn -> IO.inspect({self(), :erlang.unique_integer([:positive, :monotonic])}); :ok end
#Function<...>
iex> test.()
{#PID<0.247.0>, 1}
iex> spawn(fn ->
...>   test.()
...>   "pong" = Trigger.fire_wait(trigger, "ping")
...>   test.()
...> end)
{#PID<0.258.0>, 2}
#PID<0.258.0>
iex> "ping" = Trigger.wait_reply(trigger, "pong"); test.()
{#PID<0.247.0>, 3}
{#PID<0.258.0>, 4}