srowley

srowley

Why does starting an Agent require a function?

Why do Agent.start_link/2, get/3 and update/3 take a function to set/get state? Why not just pass/retrieve the state directly, i.e., if I want the state to be 42, just let me pass 42 instead of fn -> 42 end?

This isn’t a complaint as I am sure there is a good (maybe obvious) reason for this, this question is really just a request for a learning opportunity for me if anyone is willing to explain.

Most Liked

Nicd

Nicd

I suppose it’s so that if the agent has heavy/long initialisation/update work, it is then run in the agent and not the calling process, and the calling process can set a timeout for the work which crashes the agent.

As for the update case specifically, if the workflow was: 1) get value from agent, 2) update value locally, 3) send updated value to agent, then there is a risk of race conditions. When the update is done in the agent process, access is serialised automatically.

LostKobrakai

LostKobrakai

If you’d pass the initial state after starting the Agent process using plain messages you’ll be open to race conditions. Meaning updates might be processed before your initial state is received and applied.

dimitarvp

dimitarvp

Two reasons:

  1. Making sure the initial value gets extracted in the Agent process and not the one you are creating it in. If that analogy is easier for you, think of it in terms of multi-threading: you’re spawning thread B from thread A and want thread B to evaluate the initial value of the held state so as thread A is not blocked evaluating it.

  2. Lazy loading. You might want an Agent to actually fetch stuff from database, caches, 3rd party APIs, configuration or discovery providers etc. This circles back to the reasoning that if the initial state is expensive to compute then you’d block your original process and you don’t want that.

As for “why don’t they have an alternative API for people who know what they are doing and want to supply a static value” I’d say that it’s better safe then sorry. Writing fn -> 42 end is not much harder than 42 and you gain 100% confidence that your Agent's state will never be evaluated in the context of the caller, only in the callee (the Agent itself).

srowley

srowley

Yep, now I get it - thanks everyone!

Where Next?

Popular in Questions Top

bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
sabri
Can someone explain the settings of pool_size of Ecto in config file? and what is the recommend size? Thanks
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New

Other popular topics Top

Qqwy
Update: How to use the Blogs & Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3268 119930 1237
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New

We're in Beta

About us Mission Statement