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)
Syntax of the await-for method

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 names variable with the agent method and we set the agent state to 0.

  • Line 5: We print the current state of the names variable which is 0

  • Line 7: We use the send-off method to change the agent's state attached to the names variable. We change the names to 100; remember it was 0 initially.

  • Line 8: To enable the change to be updated to the names , we use the await-for method, which delays the program for 50 seconds and we print the output for the method, which gives a true .

  • Line 9: We print the names to ensure it was updated, giving us an updated value 100.

  • Line 10: We use the shutdown-agents to stop the agent from running. Read the shutdown-agents shot for better understanding.

  • Line 11: We call the function func.

Free Resources