watch<T> method
Future<void>
watch<T>(
- CachedCall<
T> call, - void apply(
- T value
- CacheStrategy strategy = CacheStrategy.localThenServer,
Reads call and hands each answer to apply, which assigns fields.
Typical use is the whole of a fetch:
@override
Future<void> initState() async {
await watch(api.myAssignments(), (a) => assignments = a);
}
The returned future completes once apply has taken the first answer,
so the view draws as soon as there is something to draw:
- Under CacheStrategy.localThenServer (the default) that is the saved
copy, if there is one. The view is then isRefreshing until the
server answers. If the server said exactly what was saved,
applyis not called again and nothing the person has done on screen is reset; otherwiseapplytakes the new answer and the view redraws. If the server cannot be reached, the copy stays and refreshError says why. - Under CacheStrategy.serverOnly, or with no saved copy, it is the server's answer, exactly as a plain fetch.
An error before the first answer completes the future with that error.
A saved copy that apply rejects (it throws) is set aside and the
server's answer awaited instead, so a copy that predates something just
created never shows as "not found".
Choose CacheStrategy.serverOnly where drawing a copy first would be wrong rather than briefly out of date: a screen that writes because of what it read, or one that holds the person's work.
Implementation
@protected
Future<void> watch<T>(
CachedCall<T> call,
void Function(T value) apply, {
CacheStrategy strategy = CacheStrategy.localThenServer,
}) {
final watch = _Watch();
final first = watch.first;
var shownLocal = false;
void refreshed() {
if (!watch.refreshing) return;
watch.refreshing = false;
if (!_disposed) notifyListeners();
}
watch.subscription = call
.fetch(_serverOnly ? CacheStrategy.serverOnly : strategy)
.listen(
(answer) {
if (_disposed) return;
if (answer.isLocal) {
try {
apply(answer.value);
} catch (e) {
debugPrint('$runtimeType set aside a saved copy: $e');
return;
}
shownLocal = true;
watch.refreshing = true;
first.complete();
notifyListeners();
return;
}
if (!first.isCompleted) {
try {
apply(answer.value);
first.complete();
} catch (e, stack) {
first.completeError(e, stack);
}
return;
}
if (!(shownLocal && answer.sameAsLocal)) {
try {
apply(answer.value);
} catch (e) {
debugPrint('$runtimeType could not take the server answer: $e');
_refreshError = e;
}
}
refreshed();
},
onError: (Object e, StackTrace stack) {
if (!first.isCompleted) {
first.completeError(e, stack);
return;
}
debugPrint('$runtimeType could not refresh a saved copy: $e');
_refreshError = e;
refreshed();
},
onDone: () {
_watches.remove(watch);
if (!first.isCompleted) {
first.completeError(StateError('A watched call ended without an answer'));
}
refreshed();
},
);
_watches.add(watch);
return first.future;
}