/
when_async_example.dart
82 lines (63 loc) · 1.91 KB
/
when_async_example.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
import 'dart:io';
import 'package:when_async/when_async.dart';
class FakeError extends Error {}
Future<void> example1() {
stdout.writeln('Example 1');
final _when = When.future<int>(
() => Future.delayed(
const Duration(seconds: 5),
() => 1,
),
);
final _whenError = When.future<int>(
() => Future.delayed(
const Duration(seconds: 5),
() => throw FakeError(),
),
);
const _listener1 = '(execute)';
final task1 = _when.execute(
onLoading: () => stdout.writeln('$_listener1: Loading'),
onComplete: (it) => stdout.writeln('$_listener1: Data: $it'),
onError: (e, s) => stdout.writeln('$_listener1: $e'),
onFinally: () => stdout.writeln('$_listener1: Finally'),
);
const _listener2 = '(executeWithError)';
final task2 = _whenError.execute(
onLoading: () => stdout.writeln('$_listener2: Loading'),
onComplete: (it) => stdout.writeln('$_listener2: Data: $it'),
onError: (e, s) => stdout.writeln('$_listener2: Error: $e'),
onFinally: () => stdout.writeln('$_listener2: Finally'),
);
return Future.wait([task1, task2]);
}
Future<void> example2() {
stdout.writeln('Example 2');
final _when = When.future<int>(
() => Future.delayed(
const Duration(seconds: 5),
() => 1,
),
);
final _whenError = When.future<int>(
() => Future.delayed(
const Duration(seconds: 5),
() => throw FakeError(),
),
);
const _listener1 = '(snapshot)';
final task1 = _when.snapshots(
(snapshot) => stdout.writeln('$_listener1: ${snapshot.state}'),
() => stdout.writeln('$_listener1: Finally'),
);
const _listener2 = '(snapshotWithError)';
final task2 = _whenError.snapshots(
(snapshot) => stdout.writeln('$_listener2: ${snapshot.state}'),
() => stdout.writeln('$_listener2: Finally'),
);
return Future.wait([task1, task2]);
}
Future<void> main() async {
await example1();
await example2();
}