Computed
Data is often derived from other pieces of existing data. The computed
function lets you combine the values of multiple signals into a new signal that can be reacted to, or even used by additional computeds. When the signals accessed from within a computed callback change, the computed callback is re-executed and its new return value becomes the computed signal’s value.
Computed
class extends theSignal
class, so you can use it anywhere you would use a signal.
Any signal that is accessed inside the computed
’s callback function will be automatically subscribed to and tracked as a dependency of the computed signal.
Computed signals are both lazily evaluated and memoized
Force Re-evaluation
You can force a computed signal to re-evaluate by calling its .recompute
method. This will re-run the computed callback and update the computed signal’s value.
Disposing
Auto Dispose
If a computed signal is created with autoDispose set to true, it will automatically dispose itself when there are no more listeners.
A auto disposing signal does not require its dependencies to be auto disposing. When it is disposed it will freeze its value and stop tracking its dependencies.
This means that it will no longer react to changes in its dependencies.
You can check if a signal is disposed by calling the .disposed
method.
On Dispose Callback
You can attach a callback to a signal that will be called when the signal is destroyed.
Flutter
In Flutter if you want to create a signal that automatically disposes itself when the widget is removed from the widget tree and rebuilds the widget when the signal changes, you can use the createComputed
inside a stateful widget.
No Watch
widget or extension is needed, the signal will automatically dispose itself when the widget is removed from the widget tree.
The SignalsMixin
is a mixin that automatically disposes all signals created in the state when the widget is removed from the widget tree.
Testing
Testing computed signals is possible by converting a computed to a stream and testing it like any other stream in Dart.
emitsInOrder
is a matcher that will check if the stream emits the values in the correct order which in this case is each value after a signal is updated.
You can also override the initial value of a computed signal when testing. This is is useful for mocking and testing specific value implementations.
overrideWith
returns a new computed signal with the same global id sets the value as if the computed callback returned it.