Created
August 30, 2023 06:32
-
-
Save nitaking/6c5ff1ca73317a4bf897bf1e54765bd3 to your computer and use it in GitHub Desktop.
auto_dispose_extension.dart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:async'; | |
import 'package:hooks_riverpod/hooks_riverpod.dart'; | |
extension AutoDisposeRefCache on AutoDisposeRef { | |
static final Map<String, Timer> _timersMap = {}; | |
// Keeps the provider alive for [duration] since when it was first created | |
void cacheFor(Duration duration, {String? cacheKey}) { | |
if (cacheKey != null && _timersMap.containsKey(cacheKey)) { | |
_timersMap[cacheKey]!.cancel(); | |
} | |
final link = keepAlive(); | |
final timer = Timer(duration, () { | |
link.close(); | |
if (cacheKey != null) { | |
_timersMap.remove(cacheKey); | |
} | |
}); | |
if (cacheKey != null) { | |
_timersMap[cacheKey] = timer; | |
} | |
onDispose(() { | |
timer.cancel(); | |
if (cacheKey != null) { | |
_timersMap.remove(cacheKey); | |
} | |
}); | |
} | |
// Manually clears the cache for a given key | |
/// e.g. | |
/// AutoDisposeRefCache.clearCacheForKey('some_key'); | |
static void clearCacheForKey(String key) { | |
if (_timersMap.containsKey(key)) { | |
_timersMap[key]!.cancel(); | |
_timersMap.remove(key); | |
} | |
} | |
// Manually clears the cache for this AutoDisposeRef | |
/// e.g. | |
/// ref.clearCache(); | |
static void clearCache(AutoDisposeRef ref) { | |
// clear all cache for this ref | |
_timersMap.forEach((key, timer) { | |
if (timer.isActive && timer.tick == 0) { | |
timer.cancel(); | |
_timersMap.remove(key); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment