stateAtomWithStorage<A> function

WritableAtom<A, A> stateAtomWithStorage<A>(
  1. A initialValue, {
  2. required Atom<NucleusStorage> storage,
  3. required String key,
  4. required A fromJson(
    1. dynamic json
    ),
  5. required dynamic toJson(
    1. A a
    ),
})

Create a stateAtom, except it's value is persisted to a NucleusStorage instance.

Implementation

WritableAtom<A, A> stateAtomWithStorage<A>(
  A initialValue, {
  required Atom<NucleusStorage> storage,
  required String key,
  required A Function(dynamic json) fromJson,
  required dynamic Function(A a) toJson,
}) =>
    writableAtom((get) {
      try {
        final storedValue = get(storage).get(key);
        if (storedValue != null) {
          return fromJson(storedValue);
        }
      } catch (err) {
        assert(() {
          // ignore: use_rethrow_when_possible
          throw err;
        }());
      }

      return initialValue;
    }, (get, set, setSelf, value) {
      get(storage).set(key, toJson(value));
      setSelf(value);
    });