mikera
mikera

Reputation: 106351

Updating an atom with a single value

I have a number of atoms in my code where a common requirement is to update them to a new value, regardless of the current value.

I therefore find myself writing something like this:

(swap! atom-name (fn [_] (identity new-value)))

This works but seems pretty ugly and presumably incurs a performance penalty for constructing the anonymous closure.

Is there a better way?

Upvotes: 5

Views: 143

Answers (2)

Peter Tillemans
Peter Tillemans

Reputation: 35341

You can use (compare-and-set atom old-value new-value).

But I find it strange you need to change them so much to uncorrelated values. Can't you use bindings or similar things.

Upvotes: 1

Pat Wallace
Pat Wallace

Reputation: 763

The reset! function should do this.

(reset! atom-name new-value)

Upvotes: 8

Related Questions