writableWithPrevious<T> method

WritableComputed<T> writableWithPrevious<T>(
  1. T getter(
    1. T?
    ),
  2. void setter(
    1. T
    ), {
  3. JoltDebugFn? onDebug,
})

Creates a writable computed hook with a getter that receives the previous value.

The getter function receives the previous computed value (or null on first computation) as a parameter, allowing you to implement custom logic based on the previous state. When set, the setter function is called to update the underlying dependencies. This is useful for maintaining referential equality, implementing incremental calculations, or optimizing list/map stability while still allowing writes.

Parameters:

  • getter: Function that computes the value, receiving the previous value (or null on first computation) as a parameter
  • setter: Function called when the computed value is set
  • onDebug: Optional debug callback for reactive system debugging

Returns: A WritableComputed that can access its previous value during computation

Example:

setup(context, props) {
  final signal = useSignal([5]);
  final computed = useComputed.writableWithPrevious<int>(
    (prev) {
      final newValue = signal.value[0] * 2;
      if (prev != null && prev == newValue) {
        return prev; // Return previous to maintain stability
      }
      return newValue;
    },
    (value) => signal.value = [value ~/ 2],
  );

  return () => Text('Value: ${computed.value}');
}

Implementation

WritableComputed<T> writableWithPrevious<T>(
    T Function(T?) getter, void Function(T) setter,
    {JoltDebugFn? onDebug}) {
  return useAutoDispose(
      () => WritableComputed.withPrevious(getter, setter, onDebug: onDebug));
}