Clojure – send-off

Clojure send-off

In this guide, we will discuss Clojure send-off. There are instances wherein an agent is assigned a function which is blocking in nature. A simple example is, consider you are reading contents from a file which itself is blocking in nature. So the send-off function will first immediately return the agent and continue with the file operation. When the file operation completes, it will automatically update the agent with the contents of the file.

Syntax

Following is the syntax.

(send agentname function value)

Parameters − ‘agentname’ is the agent to which the send function is being redirected to. The ‘function’ is used to determine which way the value of the agent will be changed. In our case, we will use the addition + symbol to add a value to the existing value of the agent. ‘Value’ is the value passed to the function which in turn will be used to update the value of the agent accordingly.

Return Value − First returns the agent as it is, if there is a non-blocking function. In the end, returns an agent object with a new value.

Example

An example on how this is used is shown in the following program.

(ns clojure.examples.example
   (:gen-class))
(defn Example []
   (def counter (agent 0))
   (println @counter)
   
   (send-off counter + 100)
   (println @counter)
   (println @counter))
(Example)

We are looking at the same example of incrementing the value of the counter, but from the following output it will be clear what the send-off function does.

Output

The above program produces the following output.

0
0
0

It can be seen that even though we have sent the agent a function to set the value to 100, it does not reflect immediately. The send-off function first returns the value of the agent as it is. Once the value of the agent has been set properly by Clojure, the value of the agent is then updated and we are able to see the new value of the agent.

Next Topic : Click Here

This Post Has 2 Comments

Leave a Reply