BnMcGn
BnMcGn

Reputation: 1450

Manually watch a re-frame subscription

Given a re-frame db with a value :score:

(def my-db {:score 0})

(re-frame.core/reg-sub ::score (fn [db] (:score db)))

(re-frame.core/reg-event-db
 ::initialize-db
 (fn [_ _] my-db))

(re-frame.core/reg-event-db
 ::set-score
 (fn [db [_ score]]
   (assoc db :score score)))

I expect that I should be able to subscribe to ::score and add a watcher

> (def score-atom (re-frame.core/subscribe [::score]))

> (add-watch
   score-atom
   :whatever
   (fn [_ _ _ _] (prn "here!")))

Then I should be able to trigger an update:

> (re-frame.core/dispatch [::set-score 2])
nil
> @score-atom
"here!"
2
>

Contrary to normal atom behavior, the update doesn't reach the watch until an external deref is done.

Obviously I can wrap the watch with a reagent app, but that feels heavy. How do I get the watch to trigger immediately? I would rather not manually deref the subscription each time I send a dispatch.

Upvotes: 0

Views: 380

Answers (2)

Victor Gil
Victor Gil

Reputation: 51

The subscription is only run when deref'd. It is meant to be deref'd inside a cljs react (reagent for example) component and will trigger a rerender when it is updated.

Upvotes: 0

BnMcGn
BnMcGn

Reputation: 1450

Things seem to get moving if I run (reagent.core/flush).

Upvotes: 1

Related Questions