Skip to content

Instantly share code, notes, and snippets.

@andfadeev
Created June 13, 2024 20:30
Show Gist options
  • Save andfadeev/176abae0a0d55b90492c67d2978ba6c0 to your computer and use it in GitHub Desktop.
Save andfadeev/176abae0a0d55b90492c67d2978ba6c0 to your computer and use it in GitHub Desktop.
Clojure Closeable Systems
(ns closeable-system.core
(:gen-class)
(:import (clojure.lang IDeref)
(java.io Closeable)))
(defn new-database
[db-spec]
(println "Starting database component" db-spec)
{:datasource {}})
(defn new-http-server
[dependencies config]
;; Use config to get host/port
;; Has access to dependencies (e.g database)
(println "Starting http server" config "dependencies" dependencies)
{:http-server {}})
(defn closeable
([value] (closeable value identity))
([value close] (reify
IDeref
(deref [_] value)
Closeable
(close [_] (close value)))))
(defn my-system
[config]
;; start db
;; start server
(with-open
[database (closeable
(new-database (:db-spec config))
(fn [database]
(println "Stopping database" database)))
http-server (closeable
(new-http-server
{:database @database}
(:http-server config))
(fn [http-server]
(println "Stopping http server" http-server)))]
(println "System started" @http-server)
(Thread/sleep 5000)))
(defn -main
[]
(println "Hello, World!"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment