improve provider lifetime

This commit is contained in:
Fabian Freund
2025-07-20 00:38:38 +02:00
parent dc14a7d718
commit 32e2e71c89
5 changed files with 27 additions and 7 deletions
+17
View File
@@ -0,0 +1,17 @@
import 'dart:async';
import 'package:riverpod/riverpod.dart';
extension CacheForExtension on Ref {
/// Keeps the provider alive for [duration].
void cacheFor(Duration duration) {
// Immediately prevent the state from getting destroyed.
final link = keepAlive();
// After duration has elapsed, we re-enable automatic disposal.
final timer = Timer(duration, link.close);
// Optional: when the provider is recomputed (such as with ref.watch),
// we cancel the pending timer.
onDispose(timer.cancel);
}
}