美文网首页
Rxjava实现多线程并发操作之上传多张图片

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

作者: 走在冷风中吧 | 来源:发表于2018-05-13 19:00 被阅读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())

    相关文章

      网友评论

          本文标题:Rxjava实现多线程并发操作之上传多张图片

          本文链接:https://www.haomeiwen.com/subject/tduldftx.html