mirror of
https://github.com/littensy/charm.git
synced 2026-10-21 03:36:11 +00:00
feat: initial commit
This commit is contained in:
commit
18723c1377
50 changed files with 3238 additions and 0 deletions
38
src/observe.luau
Normal file
38
src/observe.luau
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
local atom = require(script.Parent.atom)
|
||||
type Atom<T> = atom.Atom<T>
|
||||
|
||||
local subscribe = require(script.Parent.subscribe)
|
||||
|
||||
local function observe<Item, Key>(atom: Atom<{ [Key]: Item }>, factory: (value: Item, key: Key) -> () -> ()): (() -> (), () -> ())
|
||||
local connections: { [Key]: () -> () } = {}
|
||||
|
||||
local function update(state: { [Key]: Item })
|
||||
for key, disconnect in connections do
|
||||
if state[key] == nil then
|
||||
connections[key] = nil
|
||||
disconnect()
|
||||
end
|
||||
end
|
||||
|
||||
for key, value in state do
|
||||
if not connections[key] then
|
||||
connections[key] = factory(value, key)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local unsubscribe, flush = subscribe(atom, update)
|
||||
|
||||
local function cleanup()
|
||||
unsubscribe()
|
||||
for _, disconnect in connections do
|
||||
disconnect()
|
||||
end
|
||||
end
|
||||
|
||||
update(atom:get())
|
||||
|
||||
return cleanup, flush
|
||||
end
|
||||
|
||||
return observe
|
||||
Loading…
Add table
Add a link
Reference in a new issue