Skip to content

Instantly share code, notes, and snippets.

@kendru
Created June 14, 2020 03:14
Show Gist options
  • Save kendru/f51b91bcd771545df3ccaa6e3d701ea8 to your computer and use it in GitHub Desktop.
Save kendru/f51b91bcd771545df3ccaa6e3d701ea8 to your computer and use it in GitHub Desktop.
Implementation of a very basic actor system
(ns notifications.actor
(:require [reagent.core :as r]
[cljs.core.async :refer [go-loop pub sub chan <! >! put! timeout]]))
(defn actor-system []
(atom {}))
(defn mailbox [address]
[address (chan)])
(defn register-mailbox! [system mailbox]
(let [[addr ch] mailbox]
(swap! system assoc addr ch)))
(defn lookup [system addr]
(get @system addr))
(defn send-to! [system from to msg]
(when-let [ch (lookup system to)]
(put! ch [from msg])))
(defn actor [system address & {:as handlers}]
(let [mbox (mailbox address)
[_ in-ch] mbox]
(register-mailbox! system mbox)
(go-loop []
(let [m (<! in-ch)
_ (println "received" m)
[sender [type & payload]] m]
(case type
::poison-pill (println "Stopping actor @" address)
(do
(when-let [handler (get handlers type)]
(when-let [reply (apply handler payload)]
(send-to! system address sender reply)))
(recur)))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment