Skip to content

Commit 182f3f0

Browse files
committed
Add support for sequencable callable classes
This resolves issue brianegan#12 and provides a built-in workaround for brianegan/flutter_redux#6.5
1 parent 56561fb commit 182f3f0

File tree

1 file changed

+35
-5
lines changed

1 file changed

+35
-5
lines changed

lib/redux_thunk.dart

Lines changed: 35 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
library redux_thunk;
22

3+
import 'dart:async';
34
import 'package:redux/redux.dart';
45

56
/// The thunkMiddleware intercepts and calls [ThunkAction]s, which is simply a
@@ -36,13 +37,18 @@ import 'package:redux/redux.dart';
3637
///
3738
/// store.dispatch(searchResults);
3839
/// };
39-
void thunkMiddleware<State>(
40-
Store<State> store,
40+
void thunkMiddleware<State>(Store<State> store,
4141
dynamic action,
42-
NextDispatcher next,
43-
) {
42+
NextDispatcher next,) async {
4443
if (action is ThunkAction<State>) {
4544
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+
}
4652
} else {
4753
next(action);
4854
}
@@ -52,6 +58,30 @@ void thunkMiddleware<State>(
5258
/// intercepted by the the [thunkMiddleware]. It can be used to delay the
5359
/// dispatch of an action, or to dispatch only if a certain condition is met.
5460
///
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
5662
/// state if need be, or dispatch actions at the appropriate time.
5763
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

Comments
 (0)