immich/mobile/lib/modules/home/services/asset_cache.service.dart

55 lines
1.4 KiB
Dart
Raw Normal View History

2022-10-15 14:20:15 -07:00
import 'dart:convert';
2022-10-14 14:57:55 -07:00
import 'package:collection/collection.dart';
2022-10-15 14:20:15 -07:00
import 'package:flutter/foundation.dart';
2022-10-14 14:57:55 -07:00
import 'package:hive_flutter/hive_flutter.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:immich_mobile/constants/hive_box.dart';
import 'package:openapi/api.dart';
final assetCacheServiceProvider = Provider(
(ref) => AssetCacheService(),
);
class AssetCacheService {
final _cacheBox = Hive.box(assetListCacheBox);
bool isValid() {
2022-10-15 14:20:15 -07:00
return _cacheBox.containsKey(assetListCachedAssets) &&
_cacheBox.get(assetListCachedAssets) is String;
2022-10-14 14:57:55 -07:00
}
void invalidate() {
_cacheBox.clear();
}
2022-10-14 14:57:55 -07:00
void putAssets(List<AssetResponseDto> assets) {
2022-10-15 14:20:15 -07:00
final mapList = assets.map((e) => e.toJson()).toList();
final jsonString = json.encode(mapList);
2022-10-14 14:57:55 -07:00
2022-10-15 14:20:15 -07:00
_cacheBox.put(assetListCachedAssets, jsonString);
2022-10-14 14:57:55 -07:00
}
2022-10-15 14:20:15 -07:00
List<AssetResponseDto> getAssets() {
try {
final jsonString = _cacheBox.get(assetListCachedAssets);
final mapList = json.decode(jsonString) as List<dynamic>;
2022-10-14 14:57:55 -07:00
2022-10-15 14:20:15 -07:00
final responseData = mapList
.map((e) => AssetResponseDto.fromJson(e))
.whereNotNull()
.toList();
2022-10-14 14:57:55 -07:00
2022-10-15 14:20:15 -07:00
return responseData;
} catch (e) {
debugPrint(e.toString());
2022-10-14 14:57:55 -07:00
2022-10-15 14:20:15 -07:00
return [];
}
2022-10-14 14:57:55 -07:00
}
2022-10-15 14:20:15 -07:00
Future<List<AssetResponseDto>> getAssetsAsync() async {
return Future.microtask(() => getAssets());
2022-10-14 14:57:55 -07:00
}
}