-
-
Notifications
You must be signed in to change notification settings - Fork 904
/
base.dart
520 lines (463 loc) · 15.9 KB
/
base.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
part of '../async_notifier.dart';
/// A [AsyncNotifier] base class shared between family and non-family notifiers.
///
/// Not meant for public consumption outside of riverpod_generator
@internal
abstract class BuildlessAsyncNotifier<State> extends AsyncNotifierBase<State> {
@override
late final AsyncNotifierProviderElement<AsyncNotifierBase<State>, State>
_element;
@override
void _setElement(ProviderElementBase<AsyncValue<State>> element) {
_element = element
as AsyncNotifierProviderElement<AsyncNotifierBase<State>, State>;
}
@override
AsyncNotifierProviderRef<State> get ref => _element;
}
/// {@template riverpod.asyncnotifier}
/// A [Notifier] implementation that is asynchronously initialized.
///
/// It is commonly used for:
/// - Caching a network request while also allowing to perform side-effects.
/// For example, `build` could fetch information about the current "user".
/// And the [AsyncNotifier] could expose methods such as "setName",
/// to allow changing the current user name.
/// - Initializing a [Notifier] from an asynchronous source of data.
/// For example, obtaining the initial state of [Notifier] from a local database.
/// {@endtemplate}
// TODO add usage example
abstract class AsyncNotifier<State> extends BuildlessAsyncNotifier<State> {
/// {@template riverpod.asyncnotifier.build}
/// Initialize an [AsyncNotifier].
///
/// It is safe to use [Ref.watch] or [Ref.listen] inside this method.
///
/// If a dependency of this [AsyncNotifier] (when using [Ref.watch]) changes,
/// then [build] will be re-executed. On the other hand, the [AsyncNotifier]
/// will **not** be recreated. Its instance will be preserved between
/// executions of [build].
///
/// If this method throws or returns a future that fails, the error
/// will be caught and an [AsyncError] will be emitted.
/// {@endtemplate}
@visibleForOverriding
FutureOr<State> build();
}
/// {@macro riverpod.providerrefbase}
abstract class AsyncNotifierProviderRef<T> implements Ref<AsyncValue<T>> {}
/// {@template riverpod.async_notifier_provider}
/// {@endtemplate}
typedef AsyncNotifierProvider<NotifierT extends AsyncNotifier<T>, T>
= AsyncNotifierProviderImpl<NotifierT, T>;
/// The implementation of [AsyncNotifierProvider] but with loosened type constraints
/// that can be shared with [AutoDisposeAsyncNotifierProvider].
///
/// This enables tests to execute on both [AsyncNotifierProvider] and
/// [AutoDisposeAsyncNotifierProvider] at the same time.
@visibleForTesting
@internal
class AsyncNotifierProviderImpl<NotifierT extends AsyncNotifierBase<T>, T>
extends AsyncNotifierProviderBase<NotifierT, T>
with AlwaysAliveProviderBase<AsyncValue<T>>, AlwaysAliveAsyncSelector<T> {
/// {@macro riverpod.async_notifier_provider}
AsyncNotifierProviderImpl(
super._createNotifier, {
super.name,
super.from,
super.argument,
super.dependencies,
super.debugGetCreateSourceHash,
});
/// {@macro riverpod.autoDispose}
static const autoDispose = AutoDisposeAsyncNotifierProviderBuilder();
/// {@macro riverpod.family}
static const family = AsyncNotifierProviderFamilyBuilder();
@override
late final AlwaysAliveRefreshable<NotifierT> notifier =
_notifier<NotifierT, T>(this);
@override
late final AlwaysAliveRefreshable<Future<T>> future = _future<T>(this);
@override
AsyncNotifierProviderElement<NotifierT, T> createElement() {
return AsyncNotifierProviderElement._(this);
}
@override
FutureOr<T> runNotifierBuild(AsyncNotifierBase<T> notifier) {
return (notifier as AsyncNotifier<T>).build();
}
/// {@macro riverpod.overridewith}
Override overrideWith(NotifierT Function() create) {
return ProviderOverride(
origin: this,
override: AsyncNotifierProviderImpl<NotifierT, T>(
create,
from: from,
argument: argument,
),
);
}
}
/// Internal typedef for cancelling the subsription to an async operation
@internal
typedef CancelAsyncSubscription = void Function();
/// Mixin to help implement logic for listening to [Future]s/[Stream]s and setup
/// `provider.future` + convert the object into an [AsyncValue].
mixin FutureHandlerProviderElementMixin<T>
on ProviderElementBase<AsyncValue<T>> {
/// A default implementation for [ProviderElementBase.updateShouldNotify].
static bool handleUpdateShouldNotify<T>(
AsyncValue<T> previous,
AsyncValue<T> next,
) {
final wasLoading = previous.isLoading;
final isLoading = next.isLoading;
if (wasLoading || isLoading) return wasLoading != isLoading;
return true;
}
/// An internal function used to obtain the private [futureNotifier] from the mixin
static ProxyElementValueNotifier<Future<T>> futureNotifierOf<T>(
FutureHandlerProviderElementMixin<T> handler,
) {
return handler.futureNotifier;
}
/// An observable for [FutureProvider.future].
@internal
final futureNotifier = ProxyElementValueNotifier<Future<T>>();
Completer<T>? _futureCompleter;
Future<T>? _lastFuture;
CancelAsyncSubscription? _lastFutureSub;
CancelAsyncSubscription? _cancelSubscription;
/// Handles manual state change (as opposed to automatic state change from
/// listening to the [Future]).
@protected
AsyncValue<T> get state => requireState;
@protected
set state(AsyncValue<T> newState) {
// TODO assert Notifier isn't disposed
newState.map(
loading: _onLoading,
error: onError,
data: onData,
);
}
@override
bool updateShouldNotify(AsyncValue<T> previous, AsyncValue<T> next) {
return FutureHandlerProviderElementMixin.handleUpdateShouldNotify(
previous,
next,
);
}
void _onLoading(AsyncLoading<T> value, {bool seamless = false}) {
asyncTransition(value, seamless: seamless);
if (_futureCompleter == null) {
final completer = _futureCompleter = Completer();
futureNotifier.result = ResultData(completer.future);
}
}
/// Life-cycle for when an error from the provider's "build" method is received.
///
/// Might be invokved after the element is disposed in the case where `provider.future`
/// has yet to complete.
@visibleForOverriding
void onError(AsyncError<T> value, {bool seamless = false}) {
if (mounted) {
asyncTransition(value, seamless: seamless);
}
final completer = _futureCompleter;
if (completer != null) {
completer
// TODO test ignore
..future.ignore()
..completeError(
value.error,
value.stackTrace,
);
_futureCompleter = null;
// TODO SynchronousFuture.error
} else if (mounted) {
futureNotifier.result = Result.data(
// TODO test ignore
Future.error(
value.error,
value.stackTrace,
)..ignore(),
);
}
}
/// Life-cycle for when a data from the provider's "build" method is received.
///
/// Might be invokved after the element is disposed in the case where `provider.future`
/// has yet to complete.
@visibleForOverriding
void onData(AsyncData<T> value, {bool seamless = false}) {
if (mounted) {
asyncTransition(value, seamless: seamless);
}
final completer = _futureCompleter;
if (completer != null) {
completer.complete(value.value);
_futureCompleter = null;
} else if (mounted) {
futureNotifier.result = Result.data(Future.value(value.value));
}
}
/// Listens to a [Stream] and convert it into an [AsyncValue].
@preferInline
void handleStream(
Stream<T> Function() create, {
required bool didChangeDependency,
}) {
_handleAsync(didChangeDependency: didChangeDependency, ({
required data,
required done,
required error,
required last,
}) {
final rawStream = create();
final stream = rawStream.isBroadcast
? rawStream
: rawStream.asBroadcastStream(onCancel: (sub) => sub.cancel());
stream.lastCancelable(last, orElseError: _missingLastValueError);
final sub = stream.listen(data, onError: error, onDone: done);
return sub.cancel;
});
}
StateError _missingLastValueError() {
return StateError(
'The provider $origin was disposed during loading state, '
'yet no value could be emitted.',
);
}
/// Listens to a [Future] and convert it into an [AsyncValue].
@preferInline
void handleFuture(
FutureOr<T> Function() create, {
required bool didChangeDependency,
}) {
_handleAsync(didChangeDependency: didChangeDependency, ({
required data,
required done,
required error,
required last,
}) {
final futureOr = create();
if (futureOr is! Future<T>) {
data(futureOr);
done();
return null;
}
// Received a Future<T>
var running = true;
void cancel() {
running = false;
}
futureOr.then(
(value) {
if (!running) return;
data(value);
done();
},
// ignore: avoid_types_on_closure_parameters
onError: (Object err, StackTrace stackTrace) {
if (!running) return;
error(err, stackTrace);
done();
},
);
last(futureOr, cancel);
return cancel;
});
}
/// Listens to a [Future] and transforms it into an [AsyncValue].
void _handleAsync(
// Stream<T> Function({required void Function(T) fireImmediately}) create,
CancelAsyncSubscription? Function({
required void Function(T) data,
required void Function(Object, StackTrace) error,
required void Function() done,
required void Function(Future<T>, CancelAsyncSubscription) last,
})
listen, {
required bool didChangeDependency,
}) {
_onLoading(AsyncLoading<T>(), seamless: !didChangeDependency);
try {
final sub = _cancelSubscription = listen(
data: (value) {
onData(AsyncData(value), seamless: !didChangeDependency);
},
error: (error, stack) {
onError(AsyncError(error, stack), seamless: !didChangeDependency);
},
last: (last, sub) {
assert(_lastFuture == null, 'bad state');
assert(_lastFutureSub == null, 'bad state');
_lastFuture = last;
_lastFutureSub = sub;
},
done: () {
_lastFutureSub?.call();
_lastFutureSub = null;
_lastFuture = null;
},
);
assert(
sub == null || _lastFuture != null,
'An async operation is pending but the state for provider.future was not initialized.',
);
// TODO test build throws -> provider emits AsyncError synchronously & .future emits Future.error
// TODO test build resolves with error -> emits AsyncError & .future emits Future.error
// TODO test build emits value -> .future emits value & provider emits AsyncData
} catch (error, stackTrace) {
onError(
AsyncError<T>(error, stackTrace),
seamless: !didChangeDependency,
);
}
}
@override
void runOnDispose() {
// Stops listening to the previous async operation
_lastFutureSub?.call();
_lastFutureSub = null;
_lastFuture = null;
_cancelSubscription?.call();
_cancelSubscription = null;
super.runOnDispose();
}
@override
void dispose() {
final completer = _futureCompleter;
if (completer != null) {
// Whatever happens after this, the error is emitted post dispose of the provider.
// So the error doesn't matter anymore.
completer.future.ignore();
final lastFuture = _lastFuture;
if (lastFuture != null) {
// The completer will be completed by the while loop in handleStream
final cancelSubscription = _cancelSubscription;
if (cancelSubscription != null) {
completer.future
.then(
(_) {},
// ignore: avoid_types_on_closure_parameters
onError: (Object _) {},
)
.whenComplete(cancelSubscription);
}
// Prevent super.dispose from cancelling the subscription on the "last"
// stream value, so that it can be sent to `provider.future`.
_lastFuture = null;
_lastFutureSub = null;
_cancelSubscription = null;
} else {
// The listened stream completed during a "loading" state.
completer.completeError(
_missingLastValueError(),
StackTrace.current,
);
}
}
super.dispose();
}
@override
void visitChildren({
required void Function(ProviderElementBase element) elementVisitor,
required void Function(ProxyElementValueNotifier element) notifierVisitor,
}) {
super.visitChildren(
elementVisitor: elementVisitor,
notifierVisitor: notifierVisitor,
);
notifierVisitor(futureNotifier);
}
}
/// The element of [AsyncNotifierProvider].
class AsyncNotifierProviderElement<NotifierT extends AsyncNotifierBase<T>, T>
extends ProviderElementBase<AsyncValue<T>>
with FutureHandlerProviderElementMixin<T>
implements AsyncNotifierProviderRef<T> {
AsyncNotifierProviderElement._(
AsyncNotifierProviderBase<NotifierT, T> super.provider,
);
final _notifierNotifier = ProxyElementValueNotifier<NotifierT>();
@override
void create({required bool didChangeDependency}) {
final provider = this.provider as AsyncNotifierProviderBase<NotifierT, T>;
final notifierResult = _notifierNotifier.result ??= Result.guard(() {
return provider._createNotifier().._setElement(this);
});
// TODO test notifier constructor throws -> provider emits AsyncError
// TODO test notifier constructor throws -> .notifier rethrows the error
// TODO test notifier constructor throws -> .future emits Future.error
notifierResult.when(
error: (error, stackTrace) {
onError(AsyncError(error, stackTrace), seamless: !didChangeDependency);
},
data: (notifier) {
handleFuture(
() => provider.runNotifierBuild(notifier),
didChangeDependency: didChangeDependency,
);
},
);
}
@override
void visitChildren({
required void Function(ProviderElementBase element) elementVisitor,
required void Function(ProxyElementValueNotifier element) notifierVisitor,
}) {
super.visitChildren(
elementVisitor: elementVisitor,
notifierVisitor: notifierVisitor,
);
notifierVisitor(_notifierNotifier);
}
@override
bool updateShouldNotify(AsyncValue<T> previous, AsyncValue<T> next) {
return _notifierNotifier.result?.stateOrNull
?.updateShouldNotify(previous, next) ??
true;
}
}
extension<T> on Stream<T> {
void lastCancelable(
void Function(Future<T>, CancelAsyncSubscription) last, {
required Object Function() orElseError,
}) {
late StreamSubscription<T> subscription;
final completer = Completer<T>();
Result<T>? result;
subscription = listen(
(event) => result = Result.data(event),
// ignore: avoid_types_on_closure_parameters
onError: (Object error, StackTrace stackTrace) {
result = Result.error(error, stackTrace);
},
onDone: () {
if (result != null) {
result!.map(
data: (result) => completer.complete(result.state),
error: (result) {
// TODO: shoould this be reported to the zone?
completer.future.ignore();
completer.completeError(result.error, result.stackTrace);
},
);
} else {
// The error happens after the associated provider is disposed.
// As such, it's normally never read. Reporting this error as uncaught
// would cause too many false-positives. And the edge-cases that
// do reach this error will throw anyway
completer.future.ignore();
completer.completeError(
orElseError(),
StackTrace.current,
);
}
},
);
last(completer.future, subscription.cancel);
}
}