forked from vandadnp/flutter-tips-and-tricks
-
Notifications
You must be signed in to change notification settings - Fork 1
/
custom-errors-in-streams-in-dart.dart
47 lines (40 loc) · 1.02 KB
/
custom-errors-in-streams-in-dart.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
// Want to support my work 🤝? https://buymeacoffee.com/vandad
class Either<V, E extends Exception> {
final V? value;
final E? error;
const Either({this.value, this.error}) : assert((value ?? error) != null);
bool get isError => error != null;
bool get isValue => value != null;
@override
String toString() {
if (value != null) {
return "Value: $value";
} else if (error != null) {
return "Error: $error";
} else {
return 'Unknown state';
}
}
}
class DateTimeException implements Exception {
final String reason;
const DateTimeException({required this.reason});
}
Stream<Either<DateTime, DateTimeException>> getDateTime() async* {
var index = 0;
while (true) {
if (index % 2 == 0) {
yield Either(value: DateTime.now());
} else {
yield const Either(
error: DateTimeException(reason: 'Something is wrong!'),
);
}
index += 1;
}
}
void testIt() async {
await for (final value in getDateTime()) {
dev.log(value.toString());
}
}