應(yīng)用場(chǎng)景: 需要同時(shí)上傳多張圖片到服務(wù)器, 但是服務(wù)器提供的接口一次只接收一張圖片.
private fun uploadFile(paths: List<String>) {
val array = paths.toTypedArray()
Observable.fromArray(*array)
.flatMap(Function<String, Observable<MineMultiPicBean.ListBean>> {
val compressedFile = BitmapCompressUtil.load(mView as Context, File(it)).compress()
val imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), compressedFile)
val part = MultipartBody.Part.createFormData("file", compressedFile.name, imageBody)
val autoId = RequestBody.create(MediaType.parse("text/plain"), mAutoId)
val type = RequestBody.create(MediaType.parse("text/plain"), mType)
mApiService.uploadmultiImage(part, hashMapOf("autoId" to autoId, "type" to type))
.doOnTerminate { compressedFile.delete() }
.subscribeOn(Schedulers.io())
}).observeOn(AndroidSchedulers.mainThread())
.compose(mView.syncLifecycle(ActivityEvent.DESTROY))
.subscribe({
realList[realList.size - 1].apply {
template = it.template
thumb = it.thumb
templateId = it.templateId
uniqueId = it.uniqueId
autoId = it.autoId
type = it.type
check = false
}
realList.add(MineMultiPicBean.ListBean())
updateData(realList, true)
}, { mView.showDialogError(it) }, { mView.complete() })
}
使用fromArray
將List中的數(shù)據(jù)進(jìn)行單個(gè)分發(fā), 使用flatmap
達(dá)到并行效果,關(guān)鍵在于要在返回的observable, 需要重新指定執(zhí)行線程subscribeOn(Schedulers.io())