Skip to Main Content
Programming Clojure, 3rd Edition
book

Programming Clojure, 3rd Edition

by Alex Miller, Stuart Halloway, Aaron Bedra
February 2018
Intermediate to advanced content levelIntermediate to advanced
304 pages
7h 11m
English
Pragmatic Bookshelf
Content preview from Programming Clojure, 3rd Edition

Use Agents for Asynchronous Updates

Some applications have tasks that can proceed independently with minimal coordination between tasks. Clojure agents support this style of task.

Agents have much in common with refs. Like refs, you create an agent by wrapping some piece of initial state:

 (agent initial-state)

Create a counter agent that wraps an initial count of zero:

 (​def​ counter (agent 0))
 -> #​'user/counter

Once you have an agent, you can send the agent a function to update its state. send queues an update-fn to run later, on a thread in a thread pool:

 (send agent update-fn & args)

Sending to an agent is much like commuting a ref. Tell the counter to inc:

 (send counter inc)
 -> #object[clojure.lang.Agent 0x7ae288e1 {:status ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming Kotlin

Programming Kotlin

Venkat Subramaniam
Getting Clojure

Getting Clojure

Russ Olsen

Publisher Resources

ISBN: 9781680505719Errata Page