Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 86 additions & 0 deletions spec/std/observable_spec.lua
Original file line number Diff line number Diff line change
@@ -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)
11 changes: 10 additions & 1 deletion std/Observable.lua
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
Loading