Kotlin middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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