Use case for reset!


In the video What problems do Atoms solve? you show how to change a value in an atom the right way with swap! and the wrong way with reset!

I noticed that reset! has been in clojure since 1.0.

What is the use case for reset!?



Hi Jerry!

Great question :smile:

reset! is used to set the atom to a new value regardless of the current value. Since the contract of atoms is designed to keep the atom consistent, as long as the new value you’re resetting to is a consistent value, you’re ok. (reset! a x) is roughly equivalent to (swap! a (constantly x)). (constantly returns a function that always returns its argument).

The main use case is to set the atom with some value you just got. For instance, in ClojureScript I often will save the result of an ajax request to an atom using reset!. It doesn’t really make sense to use swap! there, since it’s not based on the current value. Sometimes I’ll reset! from the repl to get things back to a known state.

You could also think of reset! like you’re starting over with a fresh start. You could simulate “bankruptcy” by resetting someone’s balance to zero, regardless of the current value.