如何从onNext()访问Observable.range()索引

时间:2018-07-23 09:06:00

标签: java retrofit2 rx-java2 rx-android

我已经在RXjava代码下面编写了将图像列表上传到服务器的代码。从服务器端,它将发送一个有关上载图像链接的响应。我将这些图像保存在本地存储中,如果仅成功上传了特定图像,则应删除从本地存储中删除该图像。

    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    final String accessToken = sharedPref.getString(getString(R.string.access_token), "");
    final ArrayList<String> imageLinks = new ArrayList<>();

    Observable
            .range(0, ImageFilePaths.size())
            .flatMap(new Function<Integer, ObservableSource<ProductImageUploadResponse>>() {
                @Override
                public ObservableSource<ProductImageUploadResponse> apply(Integer index) {

                    JSONObject imageUploadKJsonObj = new JSONObject();

                    try {
                        imageUploadKJsonObj.put("version", "1.0");
                        imageUploadKJsonObj.put("action", "uploadimage");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    File file = new File(ImageFilePaths.get(index));
                    MultipartBody.Part filePart = MultipartBody.Part.createFormData("Image", file.getName(),
                            RequestBody.create(MediaType.parse("image/*"), file));
                    RequestBody accessTokenRequestBody = RequestBody.create(MediaType.parse("text/plain"), accessToken);
                    RequestBody imageUploadRequestBody = RequestBody.create(MediaType.parse("text/plain"), imageUploadKJsonObj.toString());

                    return APIservice.uploadProductImageRx(accessTokenRequestBody, imageUploadRequestBody, filePart);
                }
            })
            .retry(3)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new DisposableObserver<ProductImageUploadResponse>() {
                @Override
                public void onNext(ProductImageUploadResponse productImageUploadResponse) {

                    if(productImageUploadResponse.getResult() == 0){
                        imageLinks.add(productImageUploadResponse.getImage());
                        //Delete image from local storage
                    }
                }

                @Override
                public void onError(Throwable e) {
                    // Handel this
                }

                @Override
                public void onComplete() {
                    // Next operation
                    submitRequestEnquiryProduct(imageLinks);
                }
            });

问题是如何通过onNext()方法访问上载图像的索引以将其删除。如果可以从ImageFilePaths数组列表访问index,则可以获取路径并删除它。有没有办法做到这一点?

0 个答案:

没有答案