What is the await-for agent method in Clojure?
Overview
Clojure variables are immutable. Still, we may use an agent to mutate the storage location alongside the use of functions. The changed state of the agent is then returned, as we'll see in the example below.
The await-for method sets a time delay of milliseconds to wait for the agent to be updated. After the set time is elapsed, the agent is then updated.
Syntax
(await-for time agentname)
Parameters
The await-for method receives two parameters: the time and agentname, as shown above.
Return value
The return value of an await-for method is a boolean (True or False). It returns false due to timeout or a logical true for a successful update of the agent state.
(ns clojure.examples.example(:gen-class))(defn func [](def names (agent 0))(println @names)(send-off names + 100)(println (await-for 50 names))(println @names)(shutdown-agents))(func)
Explanation
Line 3: We define a function
func.Line 4: We define a
namesvariable with theagentmethod and we set the agent state to 0.Line 5: We print the current state of the
namesvariable which is0Line 7: We use the
send-offmethod to change the agent's state attached to thenamesvariable. We change thenamesto 100; remember it was0initially.Line 8: To enable the change to be updated to the
names, we use theawait-formethod, which delays the program for50seconds and we print the output for the method, which gives atrue.Line 9: We print the
namesto ensure it was updated, giving us an updated value100.Line 10: We use the
shutdown-agentsto stop the agent from running. Read the shutdown-agents shot for better understanding.Line 11: We call the function
func.