LazyAgent v0.1.0 LazyAgent View Source

LazyAgent

Build Status

LazyAgent wraps Elixir’s Agent library to allow delayed execution of the initial state generator function until the first time the Agent process is accessed.

It is intended to be used in test environments of applications with agents that have initialization functions that take hundreds of milliseconds or more to execute. When developing and running a subset of the test suite, these type of agents can significantly increase the time it takes to run tests, which slows down development. Using LazyAgent allows execution of only the initialization functions necessary to run the test subset.

Installation

Install LazyAgent by adding lazy_agent to your list of dependencies in mix.exs:

def deps do
  [
    {:lazy_agent, "~> 0.1.0"}
  ]
end

Configuration

To enable or disable LazyAgent, add the following to an environment configuration file:

use Mix.Config

config :lazy_agent, enabled?: true

Usage

Currently, LazyAgent only supports wrapping of Agent.start_link/2 and Agent.get/3.

 iex> {:ok, pid} = LazyAgent.start_link(fn -> 42 end)
 iex> LazyAgent.get(pid, fn state -> state end)
 42

 iex> LazyAgent.start_link(fn -> 42 end, name: :lazy)
 iex> LazyAgent.get(:lazy, fn state -> state end)
 42

Link to this section Summary

Functions

Gets an agent value via the given anonymous function, similar to Agent.get/3

Starts an agent linked to the current process with the given function, similar to Agent.start_link/2

Link to this section Types

Link to this type t() View Source
t() :: %LazyAgent{start_fun: (() -> any()), started?: boolean(), state: any()}

Link to this section Functions

Link to this function get(agent, fun, timeout \\ 5000) View Source
get(Agent.agent(), (any() -> any()), timeout()) :: any()

Gets an agent value via the given anonymous function, similar to Agent.get/3.

The function fun is sent to the agent which invokes the function passing the agent state. The result of the function invocation is returned from this function.

If the agent’s state was not previously initialized, it will be initialized exactly once for the first call to LazyAgent.get/3.

Examples

iex> {:ok, pid} = LazyAgent.start_link(fn -> 42 end)
iex> LazyAgent.get(pid, fn state -> state end)
42

iex> LazyAgent.start_link(fn -> 42 end, name: :lazy)
iex> LazyAgent.get(:lazy, fn state -> state end)
42
Link to this function start_link(fun, options \\ []) View Source
start_link((() -> any()), GenServer.options()) :: Agent.on_start()

Starts an agent linked to the current process with the given function, similar to Agent.start_link/2.