1
1
library redux_thunk;
2
2
3
+ import 'dart:async' ;
3
4
import 'package:redux/redux.dart' ;
4
5
5
6
/// The thunkMiddleware intercepts and calls [ThunkAction] s, which is simply a
@@ -36,13 +37,18 @@ import 'package:redux/redux.dart';
36
37
///
37
38
/// store.dispatch(searchResults);
38
39
/// };
39
- void thunkMiddleware <State >(
40
- Store <State > store,
40
+ void thunkMiddleware <State >(Store <State > store,
41
41
dynamic action,
42
- NextDispatcher next,
43
- ) {
42
+ NextDispatcher next,) async {
44
43
if (action is ThunkAction <State >) {
45
44
action (store);
45
+ } else if (action is ThunkCallableAction ) {
46
+ try {
47
+ dynamic result = await action.call (store);
48
+ action._completer.complete (result);
49
+ } catch (e) {
50
+ action._completer.completeError (e);
51
+ }
46
52
} else {
47
53
next (action);
48
54
}
@@ -52,6 +58,30 @@ void thunkMiddleware<State>(
52
58
/// intercepted by the the [thunkMiddleware] . It can be used to delay the
53
59
/// dispatch of an action, or to dispatch only if a certain condition is met.
54
60
///
55
- /// The ThunkFunction receives a [Store] , which it can use to get the latest
61
+ /// The ThunkAction receives a [Store] , which it can use to get the latest
56
62
/// state if need be, or dispatch actions at the appropriate time.
57
63
typedef void ThunkAction <State >(Store <State > store);
64
+
65
+ /// A base class that can be used to build a callable class that can be
66
+ /// dispatched as an action to a Redux [Store] and intercepted by the the
67
+ /// [thunkMiddleware] . It can be used to delay the dispatch of an action, or to
68
+ /// dispatch only if a certain condition is met.
69
+ ///
70
+ /// The ThunkCallableAction's [call] function receives a [Store] , which it can
71
+ /// use to get the latest state if need be, or dispatch actions at the
72
+ /// appropriate time.
73
+ ///
74
+ /// The ThunkCallableAction also exposes an [onComplete] property which returns
75
+ /// a [Future] that is completed based on the result of the [call] function.
76
+ /// This property can be used to trigger asynchronous actions in a sequence.
77
+ abstract class ThunkCallableAction <State > {
78
+ final Completer _completer = Completer <dynamic >();
79
+
80
+ /// The function that receives the [Store] for retrieving state and
81
+ /// dispatching actions.
82
+ FutureOr call (Store <State > store);
83
+
84
+ /// A [Future] that is completed once the result of calling [call] is
85
+ /// available.
86
+ Future get onComplete => _completer.future;
87
+ }
0 commit comments