diff --git a/spec/std/observable_spec.lua b/spec/std/observable_spec.lua new file mode 100644 index 0000000..54512c1 --- /dev/null +++ b/spec/std/observable_spec.lua @@ -0,0 +1,86 @@ +describe("Observable", function() + local observable + local require_utilities = require("spec.require_utilities") + + before_each(function() + require_utilities.replace_require() + require("deepcore/std/Observable") + observable = Observable() + end) + + after_each(function() + require_utilities.reset_require() + _G.Observable = nil + end) + + it("should finish notifying the original listeners when one detaches", function() + local calls = {} + local first + first = function() + table.insert(calls, "first") + observable:detach_listener(first) + end + local second = function() + table.insert(calls, "second") + end + + observable:attach_listener(first) + observable:attach_listener(second) + observable:notify() + + assert.are.same({"first", "second"}, calls) + + calls = {} + observable:notify() + assert.are.same({"second"}, calls) + end) + + it("should finish notifying a listener detached by another listener", function() + local calls = {} + local second = function() + table.insert(calls, "second") + end + local first = function() + table.insert(calls, "first") + observable:detach_listener(second) + end + + observable:attach_listener(first) + observable:attach_listener(second) + observable:notify() + + assert.are.same({"first", "second"}, calls) + + calls = {} + observable:notify() + assert.are.same({"first"}, calls) + end) + + it("should defer listeners attached while notifying", function() + local calls = {} + local attached = false + local third = function() + table.insert(calls, "third") + end + local first = function() + table.insert(calls, "first") + if not attached then + observable:attach_listener(third) + attached = true + end + end + local second = function() + table.insert(calls, "second") + end + + observable:attach_listener(first) + observable:attach_listener(second) + observable:notify() + + assert.are.same({"first", "second"}, calls) + + calls = {} + observable:notify() + assert.are.same({"first", "second", "third"}, calls) + end) +end) diff --git a/std/Observable.lua b/std/Observable.lua index 9d14b4b..8c6ecb7 100644 --- a/std/Observable.lua +++ b/std/Observable.lua @@ -47,8 +47,17 @@ function Observable:detach_listener(listener, optional_context) end end +---Checks whether this observable currently has any listeners. +---@return boolean has_listeners Whether at least one listener is attached +function Observable:has_listeners() + return table.getn(self.Listeners) > 0 +end + function Observable:notify(...) - for _, tab in ipairs(self.Listeners) do + -- Use a copy so callbacks can safely remove themselves. + local listeners = {unpack(self.Listeners)} + + for _, tab in ipairs(listeners) do local listener = tab.Listener if tab.Arg then listener(tab.Arg, unpack(arg))