Created
August 27, 2018 12:01
-
-
Save pesterhazy/aa1d8dbd43ac4b369e41101daa865525 to your computer and use it in GitHub Desktop.
Singleton functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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