Guest User

Untitled

a guest
Sep 21st, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.66 KB | None | 0 0
  1. (require '[clojure.core.memoize :as memo])
  2.  
  3. ;; suppose this is a real DB
  4. (def db (atom {}))
  5.  
  6. (defn my-get [k]
  7. ;; expensive database call
  8. (Thread/sleep 5000)
  9. (get @db k))
  10.  
  11. (def my-get-cached
  12. (memo/memo my-get))
  13.  
  14. (defn my-put
  15. [k val]
  16. (swap! db assoc k val)
  17. (memo/memo-clear! my-get-cached [k]))
  18.  
  19. (comment
  20. (my-put :foo "the value")
  21. (my-get-cached :foo) ;; wait 5 seconds, "the value"
  22. (my-get-cached :foo) ;; "the value", instantly
  23. (my-put :bar "other-value")
  24. (my-get-cached :foo) ;; "the value", still instantly
  25. (my-get-cached :bar) ;; wait 5 seconds, "other value"
  26. (my-put :foo "changed")
  27. (my-get-cached :foo) ;; wait 5 seconds, "changed"
  28. )
Add Comment
Please, Sign In to add comment