OLD | NEW |
| (Empty) |
1 | |
2 library when; | |
3 | |
4 import 'dart:async'; | |
5 | |
6 /// Registers callbacks on the result of a [callback], which may or may not be | |
7 /// a [Future]. | |
8 /// | |
9 /// If [callback] returns a future, any of [onSuccess], [onError], or | |
10 /// [onComplete] that are provided are registered on the future, | |
11 /// and the resulting future is returned. | |
12 /// | |
13 /// Otherwise, if [callback] did not throw, if [onSuccess] is provided, it is | |
14 /// called with the with the result of [callback], and the return value of | |
15 /// [onSuccess] is captured. | |
16 /// | |
17 /// Otherwise, if [onError] was provided, it is called. It can take either | |
18 /// just an error, or a stack trace as well. If [onError] was not provided, | |
19 /// the error is not caught. | |
20 /// | |
21 /// [onComplete] is then called synchronously. | |
22 /// | |
23 /// The captured value is then returned. | |
24 when(callback, {onSuccess(result), onError, onComplete}) { | |
25 var result, hasResult = false; | |
26 | |
27 try { | |
28 result = callback(); | |
29 hasResult = true; | |
30 } catch (e, s) { | |
31 if (onError != null) { | |
32 if (onError is _Unary) { | |
33 onError(e); | |
34 } else if (onError is _Binary) { | |
35 onError(e, s); | |
36 } else { | |
37 throw new ArgumentError( | |
38 '"onError" must accept 1 or 2 arguments: $onError'); | |
39 } | |
40 } else { | |
41 rethrow; | |
42 } | |
43 } finally { | |
44 if (result is Future) { | |
45 if (onSuccess != null) { | |
46 result = result.then(onSuccess); | |
47 } | |
48 if (onError != null) { | |
49 result = result.catchError(onError); | |
50 } | |
51 if (onComplete != null) { | |
52 result = result.whenComplete(onComplete); | |
53 } | |
54 } else { | |
55 if (hasResult) { | |
56 if (onSuccess != null) { | |
57 result = onSuccess(result); | |
58 } | |
59 } | |
60 if (onComplete != null) onComplete(); | |
61 } | |
62 } | |
63 | |
64 return result; | |
65 } | |
66 | |
67 typedef _Unary(x); | |
68 typedef _Binary(x, y); | |
OLD | NEW |