periodic staleData refetch functionality

+Query initialData support
+Query manual update support
+Query.reset support
This commit is contained in:
Kingkor Roy Tirtho
2022-05-28 18:28:20 +06:00
parent 4eadc99d15
commit aba6d1852b
6 changed files with 222 additions and 69 deletions
@@ -0,0 +1,13 @@
import 'package:fl_query/query_bowl.dart';
import 'package:flutter/material.dart';
class AnotherComponent extends StatelessWidget {
const AnotherComponent({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final lol = QueryBowl.of(context).getQuery<String>("greetings");
if (lol?.data == null) return const CircularProgressIndicator();
return Text("${lol!.data!} from AnotherComponent");
}
}
+33 -15
View File
@@ -1,5 +1,6 @@
import 'dart:math'; import 'dart:math';
import 'package:example/another_component.dart';
import 'package:fl_query/query_bowl.dart'; import 'package:fl_query/query_bowl.dart';
import 'package:fl_query/query_builder.dart'; import 'package:fl_query/query_builder.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
@@ -19,7 +20,10 @@ class MyApp extends StatelessWidget {
theme: ThemeData( theme: ThemeData(
primarySwatch: Colors.blue, primarySwatch: Colors.blue,
), ),
home: const QueryBowlScope(child: MyHomePage()), home: const QueryBowlScope(
staleTime: Duration(seconds: 10),
child: MyHomePage(),
),
); );
} }
} }
@@ -40,24 +44,38 @@ class _MyHomePageState extends State<MyHomePage> {
), ),
body: Column( body: Column(
children: [ children: [
QueryBuilder<String>( Row(
queryKey: "greetings", children: [
task: (queryKey) => Future.value( QueryBuilder<String>(
"Welcome ($queryKey) ${Random.secure().nextInt(100)}"), queryKey: "greetings",
builder: (context, query) { task: (queryKey) => Future.delayed(
if (query.isLoading) return const CircularProgressIndicator(); const Duration(seconds: 2),
return Row( () =>
children: [ "Welcome ($queryKey) ${Random.secure().nextInt(100)}"),
TextButton( builder: (context, query) {
if (query.isLoading || query.isRefetching) {
return const CircularProgressIndicator();
}
return TextButton(
child: Text(query.data!), child: Text(query.data!),
onPressed: () async { onPressed: () async {
await query.refetch(); await query.refetch();
}, },
), );
], },
); ),
}, QueryBuilder(
) queryKey: "failure",
task: (queryKey) =>
Future.value("[$queryKey] Failed for unknown reason"),
builder: (context, query) {
if (query.hasError) return Text(query.error);
return Text("Failure. You're a failure ${query.data}");
},
),
],
),
const AnotherComponent(),
], ],
), ),
); );
+69 -27
View File
@@ -21,6 +21,9 @@ class Query<T> extends ChangeNotifier {
QueryTaskFunction<T> task; QueryTaskFunction<T> task;
final int retries; final int retries;
final Duration retryDelay; final Duration retryDelay;
final T? _initialData;
// got from global options
final Duration _staleTime; final Duration _staleTime;
// all properties // all properties
@@ -41,13 +44,14 @@ class Query<T> extends ChangeNotifier {
required this.queryKey, required this.queryKey,
required this.task, required this.task,
required Duration staleTime, required Duration staleTime,
this.retries = 3, required this.retries,
this.retryDelay = const Duration(milliseconds: 200), required this.retryDelay,
T? initialData, T? initialData,
QueryListener<T>? onData, QueryListener<T>? onData,
QueryListener<dynamic>? onError, QueryListener<dynamic>? onError,
}) : status = QueryStatus.pending, }) : status = QueryStatus.pending,
_staleTime = staleTime, _staleTime = staleTime,
_initialData = initialData,
data = initialData, data = initialData,
_onData = onData, _onData = onData,
_onError = onError, _onError = onError,
@@ -60,49 +64,55 @@ class Query<T> extends ChangeNotifier {
bool get isLoading => bool get isLoading =>
status == QueryStatus.pending && data == null && error == null; status == QueryStatus.pending && data == null && error == null;
bool get isRefetching => bool get isRefetching =>
status == QueryStatus.refetching && data == null && error == null; status == QueryStatus.refetching && (data != null || error != null);
bool get isSucceeded => status == QueryStatus.succeed && data != null; bool get isSucceeded => status == QueryStatus.succeed && data != null;
// all methods // all methods
/// Calls the task function & doesn't check if there's already /// Calls the task function & doesn't check if there's already
/// cached data available /// cached data available
Future<void> _execute({bool isFetch = true}) async { Future<void> _execute() async {
try { try {
retryAttempts = 0; retryAttempts = 0;
status = isFetch ? QueryStatus.pending : QueryStatus.refetching;
data = await task(queryKey); data = await task(queryKey);
updatedAt = DateTime.now(); updatedAt = DateTime.now();
status = QueryStatus.succeed; status = QueryStatus.succeed;
_onData?.call(data!); _onData?.call(data!);
notifyListeners(); notifyListeners();
} catch (e) { } catch (e) {
status = QueryStatus.failed; if (retries == 0) {
error = e; status = QueryStatus.failed;
_onError?.call(e); error = e;
notifyListeners(); _onError?.call(e);
// retrying for retry count if failed for the first time notifyListeners();
while (retryAttempts <= retries) { } else {
await Future.delayed(retryDelay); // retrying for retry count if failed for the first time
try { while (retryAttempts <= retries) {
data = await task(queryKey); await Future.delayed(retryDelay);
status = QueryStatus.succeed; try {
_onData?.call(data!); data = await task(queryKey);
notifyListeners(); status = QueryStatus.succeed;
break; _onData?.call(data!);
} catch (e) { notifyListeners();
status = QueryStatus.failed; break;
error = e; } catch (e) {
retryAttempts++; if (retryAttempts == retries) {
_onError?.call(e); status = QueryStatus.failed;
notifyListeners(); error = e;
_onError?.call(e);
notifyListeners();
}
retryAttempts++;
}
} }
} }
} }
} }
Future<T?> fetch() async { Future<T?> fetch() async {
if (!_isStaleData() && hasData) { status = QueryStatus.pending;
notifyListeners();
if (!isStale && hasData) {
return data; return data;
} }
return _execute().then((_) { return _execute().then((_) {
@@ -112,11 +122,43 @@ class Query<T> extends ChangeNotifier {
} }
Future<T?> refetch() { Future<T?> refetch() {
status = QueryStatus.refetching;
refetchCount++; refetchCount++;
return _execute(isFetch: false).then((_) => data); notifyListeners();
return _execute().then((_) => data);
} }
bool _isStaleData() { /// can be used to update the data manually. Can be useful when used
/// together with mutations to perform optimistic updates or manual data
/// updates
/// For updating particular queries after a mutation using the
/// `QueryBowl.refetchQueries` is more appropriate. But this one can be
/// used when only 1 query needs get updated
///
/// Every time a new instance of data should be returned because of
/// immutability
update(FutureOr<T> Function(T? data) updateFn) async {
final newData = await updateFn(data);
if (data == newData) {
// TODO: Better Error handling & Error structure
throw Exception(
"[fl_query] new instance of data should be returned because of immutability");
}
data = newData;
status = QueryStatus.succeed;
notifyListeners();
}
void reset() {
refetchCount = 0;
data = _initialData;
error = null;
fetched = false;
status = QueryStatus.pending;
retryAttempts = 0;
}
bool get isStale {
// when current DateTime is after [update_at + stale_time] it means // when current DateTime is after [update_at + stale_time] it means
// the data has become stale // the data has become stale
return DateTime.now().isAfter(updatedAt.add(_staleTime)); return DateTime.now().isAfter(updatedAt.add(_staleTime));
+86 -26
View File
@@ -1,13 +1,20 @@
import 'dart:async';
import 'package:fl_query/query.dart'; import 'package:fl_query/query.dart';
import 'package:collection/collection.dart'; import 'package:collection/collection.dart';
import 'package:flutter/widgets.dart'; import 'package:flutter/widgets.dart';
class QueryBowlScope extends StatefulWidget { class QueryBowlScope extends StatefulWidget {
final Widget child; final Widget child;
final Duration? staleTime; final Duration staleTime;
/// used for periodically checking if any query got stale.
/// If none is supplied then half of the value of staleTime is used
final Duration? refreshInterval;
const QueryBowlScope({ const QueryBowlScope({
required this.child, required this.child,
this.staleTime, this.staleTime = const Duration(minutes: 5),
this.refreshInterval,
Key? key, Key? key,
}) : super(key: key); }) : super(key: key);
@@ -18,10 +25,46 @@ class QueryBowlScope extends StatefulWidget {
class _QueryBowlScopeState extends State<QueryBowlScope> { class _QueryBowlScopeState extends State<QueryBowlScope> {
late Set<Query> queries; late Set<Query> queries;
late Timer refreshIntervalTimer;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
queries = {}; queries = {};
refreshIntervalTimer = Timer.periodic(
widget.refreshInterval ??
Duration(
milliseconds: (widget.staleTime.inMilliseconds / 2).round(),
),
_checkAndUpdateStaleQueriesOnBg,
);
}
@override
void dispose() {
refreshIntervalTimer.cancel();
_disposeListeners();
super.dispose();
}
Future<void> _checkAndUpdateStaleQueriesOnBg([dynamic _]) async {
// checking for staled queries inside the widget as InheritedWidget
// classes has to be constant & doesn't this kind of dynamic behavior
for (final query in queries) {
if (query.isStale) await query.refetch();
}
}
void _listenToQueryUpdate() {
for (final query in queries) {
query.addListener(updateQueries);
}
}
void _disposeListeners() {
for (final query in queries) {
query.removeListener(updateQueries);
}
} }
void updateQueries() { void updateQueries() {
@@ -30,44 +73,47 @@ class _QueryBowlScopeState extends State<QueryBowlScope> {
}); });
} }
void addQuery(Query query) {
setState(() {
queries = Set.from({...queries, query});
});
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
_listenToQueryUpdate();
return QueryBowl( return QueryBowl(
onUpdate: updateQueries, onUpdate: updateQueries,
addQuery: addQuery,
queries: queries, queries: queries,
staleTime: widget.staleTime,
child: widget.child, child: widget.child,
); );
} }
} }
/// QueryBowl holds all the query related methods & properties.
/// Its responsible for creating/updating/delete queries
class QueryBowl extends InheritedWidget { class QueryBowl extends InheritedWidget {
final Set<Query> queries; final Set<Query> _queries;
final Duration staleTime; final Duration staleTime;
final void Function() onUpdate;
final void Function(Query query) _addQuery;
const QueryBowl({ const QueryBowl({
required Widget child, required Widget child,
required this.onUpdate, required final void Function() onUpdate,
required this.queries, required final void Function(Query query) addQuery,
this.staleTime = const Duration(minutes: 5), required final Set<Query> queries,
required this.staleTime,
Key? key, Key? key,
}) : super(child: child, key: key); }) : _addQuery = addQuery,
_queries = queries,
listenToQueryUpdate() { super(child: child, key: key);
for (final query in queries) {
query.addListener(onUpdate);
}
}
void disposeListeners() {
for (final query in queries) {
query.removeListener(onUpdate);
}
}
Future<T?> fetchQuery<T>(Query<T> query) async { Future<T?> fetchQuery<T>(Query<T> query) async {
final prevQuery = final prevQuery =
queries.firstWhereOrNull((q) => q.queryKey == query.queryKey); _queries.firstWhereOrNull((q) => q.queryKey == query.queryKey);
if (prevQuery is Query<T>) { if (prevQuery is Query<T>) {
if (!prevQuery.hasData) { if (!prevQuery.hasData) {
return prevQuery.fetched return prevQuery.fetched
@@ -76,23 +122,37 @@ class QueryBowl extends InheritedWidget {
} }
return prevQuery.data; return prevQuery.data;
} }
queries.add(query); _addQuery(query);
disposeListeners();
listenToQueryUpdate();
return await query.fetch(); return await query.fetch();
} }
Query<T>? getQuery<T>(String queryKey) { Query<T>? getQuery<T>(String queryKey) {
return queries.firstWhereOrNull( return _queries.firstWhereOrNull(
(query) => query.queryKey == queryKey && query is Query<T>) (query) => query.queryKey == queryKey && query is Query<T>)
as Query<T>?; as Query<T>?;
} }
int get isFetching {
return _queries.fold<int>(
0,
(acc, query) {
if (query.isLoading || query.isRefetching) acc++;
return acc;
},
);
}
void resetQuery(String queryKey) {
_queries
.firstWhereOrNull((element) => element.queryKey == queryKey)
?.reset();
}
static QueryBowl of(BuildContext context) => static QueryBowl of(BuildContext context) =>
context.dependOnInheritedWidgetOfExactType<QueryBowl>()!; context.dependOnInheritedWidgetOfExactType<QueryBowl>()!;
@override @override
bool updateShouldNotify(QueryBowl oldWidget) { bool updateShouldNotify(QueryBowl oldWidget) {
return oldWidget.staleTime != staleTime || oldWidget.queries != queries; return oldWidget.staleTime != staleTime || oldWidget._queries != _queries;
} }
} }
+20 -1
View File
@@ -6,10 +6,24 @@ class QueryBuilder<T> extends StatefulWidget {
final Widget Function(BuildContext, Query<T>) builder; final Widget Function(BuildContext, Query<T>) builder;
final QueryTaskFunction<T> task; final QueryTaskFunction<T> task;
final String queryKey; final String queryKey;
final Duration? staleTime;
final int retries;
final T? initialData;
final Duration retryDelay;
final QueryListener<T>? onData;
final QueryListener<dynamic>? onError;
const QueryBuilder({ const QueryBuilder({
required this.builder, required this.builder,
required this.task, required this.task,
required this.queryKey, required this.queryKey,
this.initialData,
this.staleTime,
this.retryDelay = const Duration(milliseconds: 200),
this.retries = 3,
this.onData,
this.onError,
Key? key, Key? key,
}) : super(key: key); }) : super(key: key);
@@ -25,7 +39,12 @@ class _QueryBuilderState<T> extends State<QueryBuilder<T>> {
await QueryBowl.of(context).fetchQuery(Query<T>( await QueryBowl.of(context).fetchQuery(Query<T>(
queryKey: widget.queryKey, queryKey: widget.queryKey,
task: widget.task, task: widget.task,
staleTime: QueryBowl.of(context).staleTime, staleTime: widget.staleTime ?? QueryBowl.of(context).staleTime,
retries: widget.retries,
initialData: widget.initialData,
retryDelay: widget.retryDelay,
onData: widget.onData,
onError: widget.onError,
)); ));
}); });
} }
+1
View File
@@ -8,6 +8,7 @@ environment:
flutter: ">=1.17.0" flutter: ">=1.17.0"
dependencies: dependencies:
async: ^2.8.2
collection: ^1.16.0 collection: ^1.16.0
flutter: flutter:
sdk: flutter sdk: flutter