1

I've a two tabbed application. Tab A is used to upload files to server. Tab B displays some results from server.

Retrofit 2 interface for file upload is as below

@Multipart
@POST("targetEndpoint")
Call<ResponseBody> uploadDocument(@Part("description") RequestBody description, @Part("fileId") RequestBody fileId, @Part MultipartBody.Part file);

And the implementation is

public void uploadDocument(File fileToUpload, String mediaType, String fileId) throws ServiceUnavailableException {
    //request body from file instance
    RequestBody requestFile = RequestBody.create(MediaType.parse(mediaType), fileToUpload);

    MultipartBody.Part body = MultipartBody.Part.createFormData("FileUpload", fileToUpload.getName(), requestFile);

    RequestBody description = RequestBody.create(MultipartBody.FORM, "File Description");
    RequestBody customerIdBody = RequestBody.create(MediaType.parse("text/plain"), fileId);

    Call<ResponseBody> call = uploadDocument(description, fileIdBody, body);

    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            Log.i(getClass().toString(), "success");
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            Log.i(getClass().toString(), "failed");
            t.printStackTrace();
        }
    });
}

File upload works well. But during the file upload, if I switch to tab B, try to fetch some data from server, it will only be processed once the upload is complete.

I understand Retrofit uses Executors for queuing requests. I see that as a limitation since the requests from tab B will be delayed until the file upload is over.

As an alternative, I could move the upload logic to a separate thread which uses generic HttpUrlConnection to push data to server.

Correct me if I'm doing wrong? Is there a way to process both requests at the same time using Retrofit 2?

Renjith
  • 3,457
  • 5
  • 46
  • 67

0 Answers0