ObservableValue
A typed value you can read, set, and observe. Adding a listener returns a cleanup function that's safe to call more than once.
local health = ObservableValue.new(100)
local cleanup = health:onChanged(function(newHealth, oldHealth)
print(`health went from {oldHealth} to {newHealth}`)
end)
health:set(80) --> health went from 100 to 80
health:update(function(current)
return current - 10
end) --> health went from 80 to 70
cleanup()
Types
Disconnect
type Disconnect = () → ()
Every listener method returns a Disconnect, the cleanup function. Call it to stop listening. It's safe to call
more than once, and can be handed to a cleanup library or returned from a React effect.
Properties
version
This item is read only and cannot be modified. Read OnlyObservableValue.version: number
Increases each time the value changes. It identifies a value even when a table was changed in place, which makes
it a useful dependency for caches, or for React's useMemo / useEffect.
Functions
new
Creates an ObservableValue holding initialValue.
get
ObservableValue:get() → TReturns the current value.
set
ObservableValue:set(newValue: T) → ()Sets the value. ObservableValue:onChanged fires if the value changed, and ObservableValue:onSet fires on every call.
INFO
Setting a table always fires onChanged, even if it's the same table, so a table you edited in place still
notifies listeners when you set it.
update
ObservableValue:update(update: (T) → T) → TSets the value to update(currentValue) and returns the new value.
health:update(function(current)
return current - 10
end)
onChanged
Calls callback whenever the value changes.
onSet
Calls callback on every ObservableValue:set, including ones that don't change the value.
promiseValue
ObservableValue:promiseValue(predicate: (T) → (boolean,R)) → TypedPromise<R>
Returns a promise that resolves with R the first time predicate(value) returns true, checking the current
value first. If predicate errors, the promise rejects with that error. Cancelling the promise stops listening.
local loaded = ObservableValue.new(false)
loaded:promiseValue(function(isLoaded)
return isLoaded, nil
end):expect() -- yields until loaded is true
observe
Calls callback straight away with the current value (oldValue is nil), then on every change.
Destroy
ObservableValue:Destroy() → ()Disconnects every listener. It works as a cleanup task in Maid, Janitor and Trove.
destroy
ObservableValue:destroy() → ()Alias of ObservableValue:Destroy.