hydrate method

Signal<T> hydrate({
  1. required String key,
  2. required T fromJson(
    1. String value
    ),
  3. required String toJson(
    1. T value
    ),
  4. SignalStorage? storage,
})

Hydrates (persists) the current signal using the provided storage or globalSignalStorage.

It immediately reads the stored value associated with key. If a value is found, it updates the signal's value silently. It then registers an Effect to automatically write any subsequent value changes back to storage.

Implementation

Signal<T> hydrate({
  required String key,
  required T Function(String value) fromJson,
  required String Function(T value) toJson,
  SignalStorage? storage,
}) {
  final activeStorage = storage ?? globalSignalStorage ?? InMemorySignalStorage();
  try {
    final stored = activeStorage.read(key);
    if (stored != null) {
      setValueSilently(fromJson(stored));
    }
  } catch (_) {
    // Ignore initial read error to allow fallback/empty state
  }

  // Reactively write updates to storage
  effect(() {
    try {
      activeStorage.write(key, toJson(value));
    } catch (_) {
      // Ignore write errors
    }
  });

  return this;
}