Skip to content

Instantly share code, notes, and snippets.

@monday8am
Last active September 24, 2018 19:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save monday8am/66b8b9a9dbe1c4ec9981e5ba11df8511 to your computer and use it in GitHub Desktop.
Save monday8am/66b8b9a9dbe1c4ec9981e5ba11df8511 to your computer and use it in GitHub Desktop.
Kotlin middleware
internal val deviceMiddleware: Middleware<AppState> = { dispatch, state ->
// dispatch: Function that send actions to the begining of the middleware list
// state: Function that returns an atomic copy of the state
// next: Function to send the action to the next middleware
// action: New incoming action
{ next ->
{ action ->
when (action) {
is DeviceConnected -> {
val currentState = state()?.appStoreState
when {
appState === currentState.WaitingForData -> {
// dispatch an action inmediatelly
// the action will be inserted at the begining of the middleware list
dispatch(SetStoreApps(Result.loading))
// Async task call
fetchStoreApps(dispatch)
}
else -> { }
}
}
is SetActiveMifare -> { }
is UpdateDelivery -> { }
}
// Dispatch the action to the next middleware
// if exist or to the reducers
next(action)
}
}
}
fun fetchAppsFromStore(dispatch: DispatchAction) {
RemoteApiManager.getStoreApps()
.compose(asRemoteRequest())
.subscribe({ result ->
// Asycn result dispatched inside an action
dispatch(SetStoreApps(Result.finished(apps)))
}, { error ->
// Asycn error dispatched inside an action
dispatch(SetStoreApps(Result.failed(reason: error)))
})
.disposed(disposer)
}
// adding multiples middlewares:
val store = Store(
reducer = ::appReducer,
state = null,
middleware = listOf(loggingMiddleware, deviceMiddleware, deliveryMiddleware))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment