Observable
Observables are objects that resolve to some value, and can be subscribed to detect updates whenver this value changes.
When setting a VirtualInstance's properties to an Observable, the properties in the mounted instance will automatically be updated by Dex to match the current value of the observable whenever its value changes.
An observable will automatically be garbage collected so long as there are no listeners are currently subscribed to it, and it is not currently being used by a mounted VirtualInstance.
Constructor
Observable is just the base class for a number of available subclasses, such as State, Stopwatch, Dict, [Alpha], etc.
Using Custom Observables should only be done with caution
Dex.CustomObservable
Dex.CustomObservable<T>(
getCurrent: () -> T,
createUpdateStream: (notifyChange: () -> ()) -> (() -> ())
) -> Observable<T>
See: Dex.CustomObservable for full documentation
CAUTION
Read the full Dex.CustomObservable documentation before writing Custom Observables; otherwise, opt for other subclasses such as State.
Types
CanBeObservable<T>
Utility type that denotes a value can be an observable. Dex also provides the utility function Dex.CoerceAsObservable for unwrapping these objects.
Functions
Current
Observable:
Current
(
) →
T
Returns the current value of the Observable.
Map
Creates a new Observable that derives its value from this Observable, using a mapping function in the domain of this Observable's value
Example of mapping a number to a currency display value:
local money = Dex.State(3)
local moneyFormatted = money:Map(function(currentMoney)
return string.format("$%0.2f", currentMoney)
end)
print(moneyFormatted:Current()) -- $3.00
Subscribe
Observable:
Subscribe
(
listener:
(
value:
T
)
→
(
)
,
immediatelyCallListener:
boolean?
) →
(
)
→
(
)
Subscribes to changes in the Observable. Returns a function that, when
called, will unsubscribe the listener from the Observable's changes. If
true
is provided as a second argument, will also call the listener once
immediately with the current value of the Observable.
CAUTION
Make sure you handle the returned "Unsubscribe" function whenever a calling
Subscribe
! If you forget to do this, you may encounter memory leaks!
Observables will remain in memory until all listeners are unsubscribed, and all VirtualInstances using it are unmounted
-- A new Observable can always be garbage collected if dereferenced
local coins = createCoinsObserver()
-- However, once we subscribe to it, it will stick
-- around in memory until we call Unsubscribe!
local unsubscribe = coins:Subscribe(function(value)
print("Coins is", value)
end, true)
task.wait(5)
-- The "coins" observable can now be garbage collected
unsubscribe()
Destroy
Observable:
Destroy
(
) →
(
)
Destroys the Observable, releasing all its resources and unsubscribing all listeners. All further Observable:Subscribe calls will error.