Last active
April 1, 2018 11:58
-
-
Save monday8am/289446f2ed0a29822f8ba8be3639239a to your computer and use it in GitHub Desktop.
Network Middleware fragment for Unidirectional Flow post.
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
// 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