mirror of
https://github.com/littensy/charm.git
synced 2026-10-20 17:51:37 +00:00
docs: document cleanup behavior
This commit is contained in:
parent
8063ea3142
commit
fa2fce090b
1 changed files with 15 additions and 4 deletions
19
README.md
19
README.md
|
|
@ -121,7 +121,7 @@ Call `subscribe` to listen for changes in an atom or selector function. When the
|
||||||
```luau
|
```luau
|
||||||
local nameAtom = atom("John")
|
local nameAtom = atom("John")
|
||||||
|
|
||||||
subscribe(nameAtom, function(name, prevName)
|
local cleanup = subscribe(nameAtom, function(name, prevName)
|
||||||
print(name)
|
print(name)
|
||||||
end)
|
end)
|
||||||
|
|
||||||
|
|
@ -135,7 +135,7 @@ local function getUppercase()
|
||||||
return string.upper(nameAtom())
|
return string.upper(nameAtom())
|
||||||
end
|
end
|
||||||
|
|
||||||
subscribe(getUppercase, function(name)
|
local cleanup = subscribe(getUppercase, function(name)
|
||||||
print(name)
|
print(name)
|
||||||
end)
|
end)
|
||||||
|
|
||||||
|
|
@ -161,7 +161,7 @@ Call `effect` to track state changes in all atoms read within the callback. The
|
||||||
```luau
|
```luau
|
||||||
local nameAtom = atom("John")
|
local nameAtom = atom("John")
|
||||||
|
|
||||||
effect(function()
|
local cleanup = effect(function()
|
||||||
print(nameAtom())
|
print(nameAtom())
|
||||||
return function()
|
return function()
|
||||||
print("Cleanup function called!")
|
print("Cleanup function called!")
|
||||||
|
|
@ -179,6 +179,17 @@ Because `effect` implicitly tracks all atoms read within the callback, it might
|
||||||
|
|
||||||
`effect` returns a cleanup function.
|
`effect` returns a cleanup function.
|
||||||
|
|
||||||
|
#### Caveats
|
||||||
|
|
||||||
|
- **If your effect calls its own cleanup function, use the `cleanup` argument.** Because effects run immediately, your effect will run before a `cleanup` function is returned. To use `cleanup` from with in the effect, use the argument passed to your effect instead:
|
||||||
|
```lua
|
||||||
|
effect(function(cleanup)
|
||||||
|
if condition() then
|
||||||
|
cleanup()
|
||||||
|
end
|
||||||
|
end)
|
||||||
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### `computed(callback, options?)`
|
### `computed(callback, options?)`
|
||||||
|
|
@ -222,7 +233,7 @@ Call `observe` to create an instance of `factory` for each key present in a dict
|
||||||
```luau
|
```luau
|
||||||
local todosAtom: Atom<{ [string]: Todo }> = atom({})
|
local todosAtom: Atom<{ [string]: Todo }> = atom({})
|
||||||
|
|
||||||
observe(todosAtom, function(todo, key)
|
local cleanup = observe(todosAtom, function(todo, key)
|
||||||
print(`Added {key}: {todo.name}`)
|
print(`Added {key}: {todo.name}`)
|
||||||
return function()
|
return function()
|
||||||
print(`Removed {key}`)
|
print(`Removed {key}`)
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue