              r
              (fn [_key _ref _old-state new-state]
                (when (not= @r new-state)
-                 (reset! r new-state))))
-
-  #_(println "2 DATA ATOM WATCHES = " (pr-str (count (.-watches r)))))
+                 (reset! r new-state)))))
 
 (defn -unconnect-atom
   [r model]

;;;;;;;;;;;;;;;;;;;;;;;;
(defn -connect-atom
  [r model dispatch-signal]
  ; sync from reference for the first time
  (dispatch-signal [::on-reset @r])

  #_(println "1 DATA ATOM WATCHES = " (pr-str (count (.-watches r))))

  ; sync model from reference
  (add-watch r
             model

                         :else
                         (app-reconcile model action)))))))

(defn -div-with-unmount-callback
  [_body unmount-cb]
  (r/create-class {:reagent-render         (fn [body _unmount-cb] (into [:div] body))
                   :component-will-unmount (fn [_this] (unmount-cb))}))

(defcard-rg
  counter-with-history
  "Preserves model value between hot reloads."
  (fn [data-atom _]
    ; Create app instance.
    (let [app (carry/app (-> counter/spec

                             ; Get model value from data atom.
                             (assoc :initial-model @data-atom)

                             ; Setup bidirectional sync with data atom.
                             (add-atom-sync data-atom)))
          [_ app-view] (carry-reagent/connect app counter/view-model counter/view)]
      ((:dispatch-signal app) :on-start)                    ; Start the app.

      ; Render app view.
      [-div-with-unmount-callback
       [app-view]

       ; Stop the app on umount/hot-reload.
       #((:dispatch-signal app) :on-stop)]))

  ; Create devcards atom with initial model value.
  (atom (:initial-model counter/spec))

  ; Card options.
  {:inspect-data true
   :history      true})

