Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (require '[clojure.core.memoize :as memo])
- ;; suppose this is a real DB
- (def db (atom {}))
- (defn my-get [k]
- ;; expensive database call
- (Thread/sleep 5000)
- (get @db k))
- (def my-get-cached
- (memo/memo my-get))
- (defn my-put
- [k val]
- (swap! db assoc k val)
- (memo/memo-clear! my-get-cached [k]))
- (comment
- (my-put :foo "the value")
- (my-get-cached :foo) ;; wait 5 seconds, "the value"
- (my-get-cached :foo) ;; "the value", instantly
- (my-put :bar "other-value")
- (my-get-cached :foo) ;; "the value", still instantly
- (my-get-cached :bar) ;; wait 5 seconds, "other value"
- (my-put :foo "changed")
- (my-get-cached :foo) ;; wait 5 seconds, "changed"
- )
Add Comment
Please, Sign In to add comment