JsonCacheMem.init constructor

JsonCacheMem.init(
  1. Map<String, Map<String, dynamic>?> initData, {
  2. JsonCache? level2,
  3. OnInitError? onInitError,
})

Initializes both the internal memory (level 1 cache) and the local storage of the user's device (level 2 cache — level2) with the contents of initData.

This method also provides a kind of transaction guarantee whereby if an error occurs while copying initData to the cache, it will attempt to revert the cache level2 to its previous state before rethrowing the exception that signaled the error. Finally, after reverting the cached data, it will invoke onInitError.

Implementation

JsonCacheMem.init(
  Map<String, Map<String, dynamic>?> initData, {
  JsonCache? level2,
  OnInitError? onInitError,
})  : _level2 = level2 ?? const JsonCacheHollow(),
      _memory = _shrMem,
      _mutex = _shrMutex {
  final initFut = _mutex.protectWrite(() async {
    final cachedKeys = <String>[];
    for (final entry in initData.entries) {
      final key = entry.key;
      final value = entry.value;
      if (value != null) {
        cachedKeys.add(key);
        try {
          await _level2.refresh(key, value);
          _memory[key] = value;
        } catch (error) {
          for (final key in cachedKeys) {
            await _level2.remove(key);
            _memory.remove(key);
          }
          rethrow;
        }
      }
    }
  });
  if (onInitError != null) {
    initFut.onError(onInitError);
  }
}