Rxjava实现多线程并发操作之上传多张图片

2018-05-13  本文已影响506人  走在冷风中吧

应用场景: 需要同时上传多张图片到服务器, 但是服务器提供的接口一次只接收一张图片.

  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中的数据进行单个分发, 使用flatmap达到并行效果,关键在于要在返回的observable, 需要重新指定执行线程subscribeOn(Schedulers.io())

上一篇 下一篇

猜你喜欢

热点阅读