Skip to content

Instantly share code, notes, and snippets.

@monday8am
Last active April 1, 2018 11:58
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/289446f2ed0a29822f8ba8be3639239a to your computer and use it in GitHub Desktop.
Save monday8am/289446f2ed0a29822f8ba8be3639239a to your computer and use it in GitHub Desktop.
Network Middleware fragment for Unidirectional Flow post.
// This middleware executes the async requests related with the Rest API
internal val networkMiddleware: Middleware<AppState> = { dispatch, state ->
{ next ->
{ action ->
when (action) {
// an async operation is called
is SetDeviceInfo -> { getDeviceDescription(deviceId = action.deviceId,
deviceInfo = action.payload,
dispatch = dispatch) }
// ... more action catches
}
// the orginal action continues on its way to other middlewares
// until reach the reducers.
next(action)
}
}
}
private fun getDeviceDescription(deviceId: DeviceId, deviceInfo: Result<DeviceInfo, Throwable>, dispatch: DispatchFunction) {
val appStoreClient = DeviceManagerApplication.appStoreClient ?: return
deviceInfo.map { info ->
val cin = Hex.encodeHex(info.deviceId.cin)
val batchId = info.batch.batchId
// Rx async operation is called
appStoreClient.getDeviceDescription(cin, batchId, null)
.compose(asRemoteRequest())
// once the result arrives, a new action is dispatched,
// passing through all middlewares again and finally reaching the reducers.
.subscribe ({ dispatch.invoke(SetDeviceDescription(deviceId, NetworkResult.ok(it.description))) },
{ dispatch.invoke(SetDeviceDescription(deviceId, NetworkResult.err(it))) })
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment