Skip to content

Hive.registerBox calls does not use generic type of the cache model. Not applicable usage for multiple cache models. #33

Description

@femrek

All box registers are registered as CacheModel type. So, multiple types are not allowed in this architecture. Following line is the point of this problem.

Hive.registerAdapter('${item.runtimeType}', item.fromDynamicJson);

My solution (is 3 steps):

  1. Create a new function called registerCacheModel in CacheManager interface.
/// Cache manager interface
abstract interface class CacheManager {
  /// Get ready to use the cache manager
  Future<void> init(); // => REMOVE ITEMS PARAMETER HERE
  
  /// Register a cache model type to the cache manager.
  void registerCacheModel<T extends CacheModel>(
      T model); // => CREATE A NEW FUNCTION

  /// Remove the stored cache
  void remove();

  /// Get the path to the cache
  String? get path;
}
  1. In HiveCacheManager (implementation of CacheManager) move the box registering section to registerCacheModel from init function.
  @override
  Future<void> init() async {
    final dir = _path ?? (await getApplicationDocumentsDirectory()).path;
    Directory(dir).createSync(recursive: true);
    Hive.defaultDirectory = dir;
    
    // move registering box section from here
  }

  @override
  void registerCacheModel<T extends CacheModel>(T modelSample) {
    Hive.registerAdapter<T>( // => Pass the generic type T to register all unique cache model classes
      modelSample.runtimeType.toString(),
      (json) => modelSample.fromJson(json) as T, // => Type casting is required.
    );
  }
  1. Register all of your cache models in ProductCache.init function.
Future<void> init() async {
  // Old method. remove this part
  // await _cacheManager.init(items: [
  //   GameSaveCacheModel.empty(),
  //   DeviceIdCacheModel.empty(),
  // ]);

  // initializes hives folder
  await _cacheManager.init();

  // register cache models instead of passing model list.
  _cacheManager
    ..registerCacheModel<GameSaveCacheModel>(GameSaveCacheModel.empty())
    ..registerCacheModel<DeviceIdCacheModel>(DeviceIdCacheModel.empty());
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions