mutate<R> method
Future<R>
mutate<R>(
- Future<
R> action(), { - void optimistic(
- PagedEdits<
Q, T> edits
- PagedEdits<
- bool invalidateAfter(
- Q query
Runs action with optimistic edits.
optimistic applies edits through PagedEdits immediately. If action
fails, they are undone (a patch is restored only when the item is still
the one that was written; a removed item is re-inserted after its former
predecessor; an inserted item is removed) and the error is rethrown.
Whatever the outcome, every touched query is invalidated (a watched one
refetches), and so is every query matching invalidateAfter — a failed
mutation may have been partly applied.
Unlike the loading methods this one rethrows: it is a mutation, not a
load. An upsertItem whose move relocated an item is undone by value,
not by position.
Implementation
Future<R> mutate<R>(
Future<R> Function() action, {
void Function(PagedEdits<Q, T> edits)? optimistic,
bool Function(Q query)? invalidateAfter,
}) async {
final undo = <void Function()>[];
final touched = <Q>{};
final edits = PagedEdits<Q, T>._(
(id, f, where) => _patchRecorded(id, f, where, undo, touched),
(id, where) => _removeRecorded(id, where, undo, touched),
(q, item, at, move) => _upsertRecorded(q, item, at, move, undo, touched),
);
try {
optimistic?.call(edits);
return await action();
} catch (_) {
for (final step in undo.reversed) {
step();
}
rethrow;
} finally {
for (final q in touched) {
invalidate(q);
}
if (invalidateAfter != null) invalidateWhere(invalidateAfter);
}
}