mirror of
https://github.com/littensy/charm.git
synced 2026-10-20 17:51:37 +00:00
* 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
34 lines
788 B
Text
34 lines
788 B
Text
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
|