fix: call listeners initially once

This commit is contained in:
Richard 2025-01-25 11:43:30 -08:00
parent 01a895e2eb
commit 052f9aaa31
2 changed files with 18 additions and 9 deletions

View file

@ -26,12 +26,14 @@ local function mapped<K0, V0, K1, V1>(callback: Selector<{ [K0]: V0 }>, mapper:
local prevMappedItems: { [K1]: V1 } = {}
local unsubscribe
unsubscribe = subscribe(callback, function(items)
if not mappedAtomRef.current then
local function listener(items: { [K0]: V0 })
local mappedAtom = mappedAtomRef.current
if not mappedAtom then
return unsubscribe()
end
local mappedItems = table.clone(store.peek(mappedAtomRef.current))
local mappedItems = table.clone(mappedAtom())
local mappedKeys = {}
-- TODO: Only call mapper if the item has changed.
@ -55,7 +57,11 @@ local function mapped<K0, V0, K1, V1>(callback: Selector<{ [K0]: V0 }>, mapper:
prevMappedItems = mappedItems
mappedAtom(mappedItems)
end)
end
unsubscribe = subscribe(callback, listener)
listener(store.peek(callback))
return mappedAtom
end

View file

@ -1,3 +1,4 @@
local store = require(script.Parent.store)
local subscribe = require(script.Parent.subscribe)
local types = require(script.Parent.types)
type Selector<T> = types.Selector<T>
@ -16,7 +17,7 @@ local function noop() end
local function observe<K, V>(callback: Selector<{ [K]: V }>, factory: (value: V, key: K) -> (() -> ())?): () -> ()
local connections: { [K]: () -> () } = {}
local unsubscribe = subscribe(callback, function(state)
local function listener(state: { [K]: V })
for key, disconnect in next, connections do
if state[key] == nil then
connections[key] = nil
@ -29,17 +30,19 @@ local function observe<K, V>(callback: Selector<{ [K]: V }>, factory: (value: V,
connections[key] = factory(value, key) or noop
end
end
end)
end
local function cleanup()
local unsubscribe = subscribe(callback, listener)
listener(store.peek(callback))
return function()
unsubscribe()
for _, disconnect in next, connections do
disconnect()
end
table.clear(connections)
end
return cleanup
end
return observe