1.2.0 permalink Arrow_down_16x16

runonce

lancet

  • (runonce function)
Create a function that will only run once. All other invocations
return the first calculated value. The function *can* have side effects
and calls to runonce *can* be composed. Deadlock is possible
if you have circular dependencies.
Returns a [has-run-predicate, reset-fn, once-fn]

0 Examples top

Log in to add / edit an example.

See Also top

Log in to add a see also.

Plus_12x12 Minus_12x12 Source lancet.clj:65 top

(defn runonce
  "Create a function that will only run once. All other invocations
  return the first calculated value. The function *can* have side effects
  and calls to runonce *can* be composed. Deadlock is possible
  if you have circular dependencies.
  Returns a [has-run-predicate, reset-fn, once-fn]"
  [function]
  (let [sentinel (Object.)
        result (atom sentinel)
        reset-fn (fn [] (reset! result sentinel))
        has-run-fn (fn [] (not= @result sentinel))]
    [has-run-fn
     reset-fn
     (fn [& args]
       (locking sentinel
         (if (= @result sentinel)
           (reset! result (function))
           @result)))]))
Vars in lancet/runonce: defn let
Used in 0 other vars

Comments top

No comments for runonce. Log in to add a comment.