implement subscriptions with callback

This commit is contained in:
Daniel Barlow 2024-04-21 13:19:17 +01:00
parent 50de1b090f
commit f9c03998b8
2 changed files with 28 additions and 13 deletions

View file

@ -20,19 +20,28 @@
(doto found (table.insert e))
found)))
(fn database []
(let [db {}]
{
:find (fn [_ terms] (find-in-database db terms))
:add (fn [_ event-string]
(let [e (parse-uevent event-string)]
(fn record-event [db subscribers str]
(let [e (parse-uevent str)]
(match e.action
:add (tset db e.path e)
:change (tset db e.path e)
; ;bind ?
;; should we do something for bind?
:remove (tset db e.path nil)
)))
)
(each [_ { : terms : callback } (ipairs subscribers)]
(if (event-matches? e terms) (callback e)))
e))
(fn database []
(let [db {}
subscribers []]
{
:find (fn [_ terms] (find-in-database db terms))
:add (fn [_ event-string] (record-event db subscribers event-string))
:at-path (fn [_ path] (. db path))
:subscribe (fn [_ callback terms]
(table.insert subscribers {: callback : terms }))
}))

View file

@ -114,10 +114,16 @@ MINOR=17")
;;; tests for subscriptions
(example "I can subscribe to some search terms")
(example "my callback is invoked when devices matching those terms are
added/changed/removed")
(example
"I can subscribe to some search terms and be notified of matching events"
(var received [])
(let [db (database)
subscriber (fn [e] (table.insert received e))]
(db:subscribe subscriber {:devname "/dev/sdb1"})
(db:add sdb1-insert)
(db:add sda-uevent)
(db:add sdb1-remove)
(expect= (# received) 2)))
(if failed (os.exit 1) (print "OK"))