AppFlowy/frontend/appflowy_flutter/lib/shared/appflowy_cache_manager.dart
Lucas.Xu 8944edf75f
feat: support clearing caches and fix unable to load image (#4809)
* feat: support clearing caches

* fix: try to clear the image cache when loading failed.

* feat: clear cache on mobile

* chore: add error log
2024-03-04 12:24:25 +08:00

62 lines
1.3 KiB
Dart

import 'package:appflowy_backend/log.dart';
import 'package:path_provider/path_provider.dart';
class FlowyCacheManager {
final _caches = <ICache>[];
// if you add a new cache, you should register it here.
void registerCache(ICache cache) {
_caches.add(cache);
}
void unregisterAllCache(ICache cache) {
_caches.clear();
}
Future<void> clearAllCache() async {
try {
for (final cache in _caches) {
await cache.clearAll();
}
Log.info('Cache cleared');
} catch (e) {
Log.error(e);
}
}
Future<int> getCacheSize() async {
try {
int tmpDirSize = 0;
for (final cache in _caches) {
tmpDirSize += await cache.cacheSize();
}
Log.info('Cache size: $tmpDirSize');
return tmpDirSize;
} catch (e) {
Log.error(e);
return 0;
}
}
}
abstract class ICache {
Future<int> cacheSize();
Future<void> clearAll();
}
class TemporaryDirectoryCache implements ICache {
@override
Future<int> cacheSize() async {
final tmpDir = await getTemporaryDirectory();
final tmpDirStat = await tmpDir.stat();
return tmpDirStat.size;
}
@override
Future<void> clearAll() async {
final tmpDir = await getTemporaryDirectory();
await tmpDir.delete(recursive: true);
}
}