11package org.reduxkotlin
22
3- typealias Thunk = (Dispatcher , GetState , Any? ) -> Any
3+ /* *
4+ * Thunk middleware for async action dispatches.
5+ * Usage:
6+ * val store = createStore(myReducer, initialState,
7+ * applyMiddleware(thunk, myMiddleware))
8+ *
9+ * val myNetworkThunk(query: String) = createThunk { dispatch, getState, extraArgument ->
10+ * launch {
11+ * dispatch(LoadingAction())
12+ * //do async stuff
13+ * val result = api.fetch(query)
14+ * dispatch(CompleteAction(result))
15+ * }
16+ * }
17+ *
18+ * store.dispatch(myNetworkThunk("query"))
19+ */
20+ fun createThunkMiddleware (extraArgument : Any? = null): ThunkMiddleware =
21+ { store ->
22+ { next: Dispatcher ->
23+ { action: Any ->
24+ if (action is Thunk ) {
25+ try {
26+ action.dispatch(store.dispatch, store.getState, extraArgument)
27+ } catch (e: Exception ) {
28+ // Logger.d("Dispatching functions must use type Thunk: " + e.message)
29+ throw IllegalArgumentException ()
30+ }
31+ } else {
32+ next(action)
33+ }
34+ }
35+ }
36+ }
37+
438typealias ThunkMiddleware = Middleware
39+ val thunk = createThunkMiddleware()
40+
41+ fun ThunkMiddleware.withExtraArgument (arg : Any? ) = createThunkMiddleware(arg)
42+
43+ /* *
44+ * Interface that can be dispatched and handled by ThunkMiddleware.
45+ * Asynchronous operations and Actions may be dispatched from within a Thunk.
46+ * Due to limitation of K/N a type alias does not work currently.
47+ */
48+ interface Thunk {
49+ fun dispatch (dispatch : Dispatcher , getState : GetState , extraArgument : Any? ): Any
50+ }
51+ /* *
52+ * Convenience function for creating thunks.
53+ * Usage:
54+ * val myThunk = createThunk { dispatch, getState, extraArgument ->
55+ * //do async stuff
56+ * dispatch(NewAction())
57+ * }
58+ *
59+ * ....
60+ *
61+ * store.dispatch(myThunk)
62+ *
63+ * DEV NOTE: This will not be needed if/when typealias for Thunk works with K/N
64+ */
65+ fun createThunk (thunkLambda : (dispatch: Dispatcher , getState: GetState , extraArgument: Any? ) -> Any ): Thunk {
66+ return object : Thunk {
67+ override fun dispatch (dispatch : Dispatcher , getState : GetState , extraArgument : Any? ): Any =
68+ thunkLambda(dispatch, getState, extraArgument)
69+ }
70+ }
71+
72+ /*
73+ * Unable to use Thunk as a typealias currently do to a limitation of kotlin native.
74+ * Leaving code here as a reference to revisit.
75+ * /
76+ typealias Thunk = (Dispatcher, GetState, Any?) -> Any
577fun createThunkMiddleware(extraArgument: Any? = null): ThunkMiddleware =
678 { store ->
779 { next: Dispatcher ->
@@ -19,7 +91,6 @@ fun createThunkMiddleware(extraArgument: Any? = null): ThunkMiddleware =
1991 }
2092 }
2193 }
94+ */
2295
23- val thunk = createThunkMiddleware()
2496
25- fun ThunkMiddleware.withExtraArgument (arg : Any? ) = createThunkMiddleware(arg)
0 commit comments