How stateful watches work in Hawk
masterHawk allows you to maintain state across events using the :context key.
- Initialization: Provide a
:contextfunction. This function is called once when the watch starts. It receives the current context (initiallynil) and should return the initial state value. - State Updates: The
:handlerfunction receives the current state as its first argument. To update the state, the:handlermust return the new state value.
Watch Groups and Concurrency:
hawk/watch!accepts multiple arrays of watch specs.- Within an array: All specs share the same state, and events are processed sequentially.
- Between arrays: Each array (group) gets its own independent state, and groups are processed in parallel.
;; Example of stateful watch: incrementing a counter on every event
(hawk/watch! [{:paths ["src/main/hawk"]
:context (constantly 1)
:handler (fn [ctx _] (inc ctx))}])
;; Example of multiple groups with independent states
(hawk/watch!
;; Group 1: Shared state, sequential processing
[{:paths ["src/main/hawk"]
:context (constantly 1)
:handler (fn [ctx _]
(println "I'm always first!")
(inc ctx))}
{:paths ["src/test/hawk"]
:context (fn [ctx] (inc ctx))
:handler (fn [_ _]
(println "I'm always second place."))}]
;; Group 2: Separate state, parallel to Group 1
[{:paths ["src/main/hawk"]
:context (constantly 3)
:handler (fn [_ _]
(println "I'm also always first!"))}])