Fork me on GitHub
#beginners
<
2021-08-21
>
Vlad Kryvokoniev12:08:26

Hi, Do you guys have an idea how to make it more concise, readable?

(swap! app-state assoc :twitch-clips (conj (:twitch-clips @app-state) clip-link))

tschady12:08:43

use update instead of assoc

Vlad Kryvokoniev12:08:34

can u explain why please?

tschady12:08:18

user=> (def a (atom {:b [1]}))
#'user/a
user=> @a
{:b [1]}
user=> (swap! a update :b conj 2)
{:b [1 2]}

ghadi12:08:45

Because it’s not atomic if you do two atom operations- @ and swap!

ghadi12:08:54

That’s a race condition

ghadi12:08:20

With a single op it’s atomic

Vlad Kryvokoniev13:08:56

@U1Z392WMQ thanks for explanation. @U050ECB92 do you mean I should remove the dereference character from there?

ghadi13:08:02

Yes. You’re deferencing and swapping - and swap always passes the derefenced value to the function passed in

Emi Gal17:08:39

I’ve done a bit of googling but couldn’t find much useful info: what are the advantages / disadvantages of using update and update-in vs assoc and assoc-in to update data in a map?

didibus03:08:09

Just a different interface for a similar behavior. update takes a function of the current value, assoc takes a new value to replace the existing one with

pavlosmelissinos06:08:16

Given a map m, (update m :clicks inc) is equivalent to (assoc m :clicks (inc (:clicks m))) Both are correct but the former is arguably easier to read My rule of thumb is: if the new value depends on the old value (like didibus said), update probably makes more sense, otherwise use assoc

respatialized17:08:21

You need get / get-in to find the value you want to assoc if you intend to call a function on it before assoc ing it into the updated map. update makes this slightly less verbose. Under the hood it's just get and assoc: https://github.com/clojure/clojure/blob/clojure-1.10.1/src/clj/clojure/core.clj#L6188