implement unsubscribe

and add ids to subscribe so that there's a unique identifier
to pass to unsubscribe
This commit is contained in:
Daniel Barlow 2024-04-23 20:12:46 +01:00
parent cbb1de804e
commit 52eb283a26
2 changed files with 16 additions and 4 deletions

View file

@ -28,7 +28,7 @@
;; should we do something for bind?
:remove (tset db e.path nil)
)
(each [_ { : terms : callback } (ipairs subscribers)]
(each [_ { : terms : callback } (pairs subscribers)]
(if (event-matches? e terms) (callback e)))
e))
@ -39,8 +39,9 @@
: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 }))
:subscribe (fn [_ id callback terms]
(tset subscribers id {: callback : terms }))
:unsubscribe (fn [_ id] (tset subscribers id nil))
}))

View file

@ -119,11 +119,22 @@ MINOR=17")
(var received [])
(let [db (database)
subscriber (fn [e] (table.insert received e))]
(db:subscribe subscriber {:devname "/dev/sdb1"})
(db:subscribe :me subscriber {:devname "/dev/sdb1"})
(db:add sdb1-insert)
(db:add sda-uevent)
(db:add sdb1-remove)
(expect= (# received) 2)))
(example
"I can unsubscribe after subscribing"
(var received [])
(let [db (database)
subscriber (fn [e] (table.insert received e))]
(db:subscribe :me subscriber {:devname "/dev/sdb1"})
(db:unsubscribe :me)
(db:add sdb1-insert)
(db:add sda-uevent)
(db:add sdb1-remove)
(expect= (# received) 0)))
(if failed (os.exit 1) (print "OK"))