hydrate method
Signal<T>
hydrate({
- required String key,
- required T fromJson(
- String value
- required String toJson(
- T value
- 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 a lightweight
change listener to write subsequent values without preventing auto-disposal.
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 ?? _fallbackSignalStorage;
try {
final stored = activeStorage.read(key);
if (stored != null) {
setValueSilently(fromJson(stored));
}
} catch (_) {
// Ignore initial read error to allow fallback/empty state
}
void persist(T previous, T current) {
try {
activeStorage.write(key, toJson(current));
} catch (_) {
// Ignore write errors
}
}
// Persist the hydrated/default value immediately, then future changes.
persist(value, value);
addChangeListener(persist);
return this;
}