charm/src/effect.luau
richard a90d131fed
feat: allow conditional dependencies (#4)
* feat: allow conditional dependencies

* docs: remove conditional deps warnings

* fix: allow nested captures

* docs: add dev flag

* fix: `try()` uses pcall if passed `finally()`

* docs: interval is optional

* docs: update readme

* docs: add client/server tags
2024-06-11 17:13:43 -07:00

34 lines
788 B
Lua

local store = require(script.Parent.store)
type Cleanup = () -> ()
--[=[
Runs the given callback immediately and whenever any atom it depends on
changes. Returns a cleanup function that unsubscribes the callback.
@param callback The function to run.
@return A function that unsubscribes the callback.
]=]
local function effect(callback: () -> any): () -> ()
local dependencies, cleanup = store.capture(callback)
local function listener()
if cleanup then
cleanup()
end
dependencies, cleanup = store.reconnect(callback, dependencies, listener)
end
store.connect(dependencies, listener)
return function()
store.disconnect(dependencies, listener)
if cleanup then
cleanup()
end
end
end
return effect :: (callback: (() -> ()) | (() -> Cleanup)) -> Cleanup