From 52eb283a26ad7a41838e186da69ba5237a208c1b Mon Sep 17 00:00:00 2001 From: Daniel Barlow Date: Tue, 23 Apr 2024 20:12:46 +0100 Subject: [PATCH] implement unsubscribe and add ids to subscribe so that there's a unique identifier to pass to unsubscribe --- pkgs/devout/devout.fnl | 7 ++++--- pkgs/devout/test.fnl | 13 ++++++++++++- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/pkgs/devout/devout.fnl b/pkgs/devout/devout.fnl index b6041ed..ea34409 100644 --- a/pkgs/devout/devout.fnl +++ b/pkgs/devout/devout.fnl @@ -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)) })) diff --git a/pkgs/devout/test.fnl b/pkgs/devout/test.fnl index 8c61541..2daff4d 100644 --- a/pkgs/devout/test.fnl +++ b/pkgs/devout/test.fnl @@ -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"))