Skip to content

Instantly share code, notes, and snippets.

@pesterhazy
Created August 27, 2018 12:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pesterhazy/aa1d8dbd43ac4b369e41101daa865525 to your computer and use it in GitHub Desktop.
Save pesterhazy/aa1d8dbd43ac4b369e41101daa865525 to your computer and use it in GitHub Desktop.
Singleton functions
(defn singleton-fn
"Returns a function that creates a resource. When called a second time,
calls dispose-fn before recreating the resource"
[create-fn dispose-fn]
(let [!state (atom nil)]
(fn [& args]
(when-let [state @!state]
(dispose-fn state))
(let [result (apply create-fn args)]
(reset! !state (or result ::initialized))))))
;; example
(defonce make-timer (singleton-fn #(js/setInterval (fn [] (js/console.log "tick")) %)
#(js/clearInterval %)))
(def my-timer (make-timer 5000))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment