local function observable(val)
local new_observable = {
value = val,
observers = {},
subscribe = function(self, observer)
table.insert(self.observers, observer)
end,
unsubscribe = function(self, observer)
for i, obs in ipairs(self.observers) do
if obs == observer then
table.remove(self.observers, i)
break
end
end
end,
publish = function(self, data)
for _, observer in ipairs(self.observers) do
observer(data)
end
end,
}
return new_observable
end
local PubSub = {}
local topics = {}
function PubSub.subscribe(topic, callback)
if not topics[topic] then
topics[topic] = {}
end
table.insert(topics[topic], callback)
end
function PubSub.unsubscribe(topic, callback)
if not topics[topic] then
return
end
if callback then
for i, cb in ipairs(topics[topic]) do
if cb == callback then
table.remove(topics[topic], i)
break
end
end
else
table.remove(topics[topic])
end
end
function PubSub.publish(topic, data)
if not topics[topic] then
return
end
local subs = {}
for _, cb in ipairs(topics[topic]) do
table.insert(subs, cb)
end
for _, callback in ipairs(subs) do
callback(data, topic)
end
end
return {
observable = observable,
pubsub = PubSub,
}