/
signal.dart
447 lines (433 loc) · 12 KB
/
signal.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
import 'dart:async';
import '../core/signals.dart';
import 'state.dart';
/// {@template signal}
/// `AsyncState` is class commonly used with Future/Stream signals to represent the states the signal can be in.
///
/// ## AsyncSignal
///
/// `AsyncState` is the default state if you want to create a `AsyncSignal` directly:
///
/// ```dart
/// final s = asyncSignal(AsyncState.data(1));
/// s.value = AsyncState.loading(); // or AsyncLoading();
/// s.value = AsyncState.error('Error', null); // or AsyncError();
/// ```
///
/// ## AsyncState
///
/// `AsyncState` is a sealed union made up of `AsyncLoading`, `AsyncData` and `AsyncError`.
///
/// ### .future
///
/// Sometimes you need to await a signal value in a async function until a value is completed and in this case use the .future getter.
///
/// ```dart
/// final s = asyncSignal<int>(AsyncState.loading());
/// s.value = AsyncState.data(1);
/// await s.future; // Waits until data or error is set
/// ```
///
/// ### .isCompleted
///
/// Returns true if the future has completed with an error or value:
///
/// ```dart
/// final s = asyncSignal<int>(AsyncState.loading());
/// s.value = AsyncState.data(1);
/// print(s.isCompleted); // true
/// ```
///
/// ### .hasValue
///
/// Returns true if a value has been set regardless of the state.
///
/// ```dart
/// final s = asyncSignal<int>(AsyncState.loading());
/// print(s.hasValue); // false
/// s.value = AsyncState.data(1);
/// print(s.hasValue); // true
/// ```
///
/// ### .hasError
///
/// Returns true if a error has been set regardless of the state.
///
/// ```dart
/// final s = asyncSignal<int>(AsyncState.loading());
/// print(s.hasError); // false
/// s.value = AsyncState.error('error', null);
/// print(s.hasError); // true
/// ```
///
/// ### .isRefreshing
///
/// Returns true if the state is refreshing with a loading flag, has a value or error and is not the loading state.
///
/// ```dart
/// final s = asyncSignal<int>(AsyncState.loading());
/// print(s.isRefreshing); // false
/// s.value = AsyncState.error('error', null, isLoading: true);
/// print(s.isRefreshing); // true
/// s.value = AsyncState.data(1, isLoading: true);
/// print(s.isRefreshing); // true
/// ```
///
/// ### .isReloading
///
/// Returns true if the state is reloading with having a value or error, and is the loading state.
///
/// ```dart
/// final s = asyncSignal<int>(AsyncState.loading());
/// print(s.isReloading); // false
/// s.value = AsyncState.loading(data: 1);
/// print(s.isReloading); // true
/// s.value = AsyncState.loading(error: ('error', null));
/// print(s.isReloading); // true
/// ```
///
/// ### .requireValue
///
/// Force unwrap the value of the state and throw an error if it has an error or is null.
///
/// ```dart
/// final s = asyncSignal<int>(AsyncState.data(1));
/// print(s.requireValue); // 1
/// ```
///
/// ### .value
///
/// Return the current value if exists.
///
/// ```dart
/// final s = asyncSignal<int>(AsyncState.data(1));
/// print(s.value); // 1 or null
/// ```
///
/// ### .error
///
/// Return the current error if exists.
///
/// ```dart
/// final s = asyncSignal<int>(AsyncState.error('error', null));
/// print(s.error); // 'error' or null
/// ```
///
/// ### .stackTrace
///
/// Return the current stack trace if exists.
///
/// ```dart
/// final s = asyncSignal<int>(AsyncState.error('error', StackTrace(...)));
/// print(s.stackTrace); // StackTrace(...) or null
/// ```
///
/// ### .map
///
/// If you want to handle the states of the signal `map` will enforce all branching.
///
/// ```dart
/// final signal = asyncSignal<int>(AsyncState.data(1));
/// signal.value.map(
/// data: (value) => 'Value: $value',
/// error: (error, stackTrace) => 'Error: $error',
/// loading: () => 'Loading...',
/// );
/// ```
///
/// ### .maybeMap
///
/// If you want to handle some of the states of the signal `maybeMap` will provide a default and optional overrides.
///
/// ```dart
/// final signal = asyncSignal<int>(AsyncState.data(1));
/// signal.value.maybeMap(
/// data: (value) => 'Value: $value',
/// orElse: () => 'Loading...',
/// );
/// ```
///
/// ### Pattern Matching
///
/// Instead of `map` and `maybeMap` it is also possible to use [dart switch expressions](https://dart.dev/language/patterns) to handle the branching.
///
/// ```dart
/// final signal = asyncSignal<int>(AsyncState.data(1));
/// final value = switch (signal.value) {
/// AsyncData<int> data => 'value: ${data.value}',
/// AsyncError<int> error => 'error: ${error.error}',
/// AsyncLoading<int>() => 'loading',
/// };
/// ```
/// @link https://dartsignals.dev/dart/async/state
/// {@endtemplate}
class AsyncSignal<T> extends ValueSignal<AsyncState<T>> {
/// A [Signal] that stores value in [AsyncState]
AsyncSignal(
super.value, {
super.debugLabel,
super.equality,
super.autoDispose,
}) : _initialValue = value;
final AsyncState<T> _initialValue;
bool _initialized = false;
Completer<bool> _completer = Completer<bool>();
/// The future of the signal completer
Future<T> get future async {
value;
await _completer.future;
return value.requireValue;
}
/// Returns true if the signal is completed an error or data
bool get isCompleted {
value;
return _completer.isCompleted;
}
/// Set the error with optional stackTrace to [AsyncError]
void setError(Object error, [StackTrace? stackTrace]) {
batch(() {
value = AsyncState.error(error, stackTrace);
if (_completer.isCompleted) _completer = Completer<bool>();
_completer.complete(true);
});
}
/// Set the value to [AsyncData]
void setValue(T value) {
batch(() {
this.value = AsyncState.data(value);
if (_completer.isCompleted) _completer = Completer<bool>();
_completer.complete(true);
});
}
/// Set the loading state to [AsyncLoading]
void setLoading([AsyncState<T>? state]) {
batch(() {
value = state ?? AsyncState.loading();
_completer = Completer<bool>();
});
}
/// Reset the signal to the initial value
void reset([AsyncState<T>? value]) {
batch(() {
this.value = value ?? _initialValue;
_initialized = false;
if (_completer.isCompleted) _completer = Completer<bool>();
});
}
/// Initialize the signal
void init() async {
if (_initialized) return;
_initialized = true;
}
/// Reload the future
Future<void> reload() async {
value = switch (value) {
AsyncData<T> data => AsyncLoading<T>(
value: data.value,
hasValue: true,
isLoading: false,
),
AsyncError<T> err => AsyncLoading<T>(
error: (err.error, err.stackTrace),
hasError: true,
isLoading: false,
),
AsyncLoading<T>() => AsyncLoading<T>(),
};
}
/// Refresh the future
Future<void> refresh() async {
value = switch (value) {
AsyncData<T> data => AsyncData<T>(
data.value,
isLoading: true,
),
AsyncError<T> err => AsyncError<T>(
err.error,
err.stackTrace,
isLoading: true,
),
AsyncLoading<T>() => AsyncLoading<T>(),
};
}
@override
AsyncState<T> get value {
init();
return super.value;
}
/// Returns the value of the signal
T get requireValue => super.value.requireValue;
}
/// {@template signal}
/// `AsyncState` is class commonly used with Future/Stream signals to represent the states the signal can be in.
///
/// ## AsyncSignal
///
/// `AsyncState` is the default state if you want to create a `AsyncSignal` directly:
///
/// ```dart
/// final s = asyncSignal(AsyncState.data(1));
/// s.value = AsyncState.loading(); // or AsyncLoading();
/// s.value = AsyncState.error('Error', null); // or AsyncError();
/// ```
///
/// ## AsyncState
///
/// `AsyncState` is a sealed union made up of `AsyncLoading`, `AsyncData` and `AsyncError`.
///
/// ### .future
///
/// Sometimes you need to await a signal value in a async function until a value is completed and in this case use the .future getter.
///
/// ```dart
/// final s = asyncSignal<int>(AsyncState.loading());
/// s.value = AsyncState.data(1);
/// await s.future; // Waits until data or error is set
/// ```
///
/// ### .isCompleted
///
/// Returns true if the future has completed with an error or value:
///
/// ```dart
/// final s = asyncSignal<int>(AsyncState.loading());
/// s.value = AsyncState.data(1);
/// print(s.isCompleted); // true
/// ```
///
/// ### .hasValue
///
/// Returns true if a value has been set regardless of the state.
///
/// ```dart
/// final s = asyncSignal<int>(AsyncState.loading());
/// print(s.hasValue); // false
/// s.value = AsyncState.data(1);
/// print(s.hasValue); // true
/// ```
///
/// ### .hasError
///
/// Returns true if a error has been set regardless of the state.
///
/// ```dart
/// final s = asyncSignal<int>(AsyncState.loading());
/// print(s.hasError); // false
/// s.value = AsyncState.error('error', null);
/// print(s.hasError); // true
/// ```
///
/// ### .isRefreshing
///
/// Returns true if the state is refreshing with a loading flag, has a value or error and is not the loading state.
///
/// ```dart
/// final s = asyncSignal<int>(AsyncState.loading());
/// print(s.isRefreshing); // false
/// s.value = AsyncState.error('error', null, isLoading: true);
/// print(s.isRefreshing); // true
/// s.value = AsyncState.data(1, isLoading: true);
/// print(s.isRefreshing); // true
/// ```
///
/// ### .isReloading
///
/// Returns true if the state is reloading with having a value or error, and is the loading state.
///
/// ```dart
/// final s = asyncSignal<int>(AsyncState.loading());
/// print(s.isReloading); // false
/// s.value = AsyncState.loading(data: 1);
/// print(s.isReloading); // true
/// s.value = AsyncState.loading(error: ('error', null));
/// print(s.isReloading); // true
/// ```
///
/// ### .requireValue
///
/// Force unwrap the value of the state and throw an error if it has an error or is null.
///
/// ```dart
/// final s = asyncSignal<int>(AsyncState.data(1));
/// print(s.requireValue); // 1
/// ```
///
/// ### .value
///
/// Return the current value if exists.
///
/// ```dart
/// final s = asyncSignal<int>(AsyncState.data(1));
/// print(s.value); // 1 or null
/// ```
///
/// ### .error
///
/// Return the current error if exists.
///
/// ```dart
/// final s = asyncSignal<int>(AsyncState.error('error', null));
/// print(s.error); // 'error' or null
/// ```
///
/// ### .stackTrace
///
/// Return the current stack trace if exists.
///
/// ```dart
/// final s = asyncSignal<int>(AsyncState.error('error', StackTrace(...)));
/// print(s.stackTrace); // StackTrace(...) or null
/// ```
///
/// ### .map
///
/// If you want to handle the states of the signal `map` will enforce all branching.
///
/// ```dart
/// final signal = asyncSignal<int>(AsyncState.data(1));
/// signal.value.map(
/// data: (value) => 'Value: $value',
/// error: (error, stackTrace) => 'Error: $error',
/// loading: () => 'Loading...',
/// );
/// ```
///
/// ### .maybeMap
///
/// If you want to handle some of the states of the signal `maybeMap` will provide a default and optional overrides.
///
/// ```dart
/// final signal = asyncSignal<int>(AsyncState.data(1));
/// signal.value.maybeMap(
/// data: (value) => 'Value: $value',
/// orElse: () => 'Loading...',
/// );
/// ```
///
/// ### Pattern Matching
///
/// Instead of `map` and `maybeMap` it is also possible to use [dart switch expressions](https://dart.dev/language/patterns) to handle the branching.
///
/// ```dart
/// final signal = asyncSignal<int>(AsyncState.data(1));
/// final value = switch (signal.value) {
/// AsyncData<int> data => 'value: ${data.value}',
/// AsyncError<int> error => 'error: ${error.error}',
/// AsyncLoading<int>() => 'loading',
/// };
/// ```
/// @link https://dartsignals.dev/dart/async/state
/// {@endtemplate}
AsyncSignal<T> asyncSignal<T>(
AsyncState<T> value, {
String? debugLabel,
SignalEquality<AsyncState<T>>? equality,
bool autoDispose = false,
}) {
return AsyncSignal<T>(
value,
debugLabel: debugLabel,
equality: equality,
autoDispose: autoDispose,
);
}