javaandroidretrofit2progressdialogrequest-cancelling

How is it possible to cancel a retrofit call from outside the respected thread?


I'm creating such an on-thread issue of retrofit:

new Thread(new Runnable() {
                @Override
                public void run() {
                    mService.uploadFile(body)
                            .enqueue(new Callback<String>() {
                                @Override
                                public void onResponse(final Call<String> call, Response<String> response) {

                                    progressDialog.dismiss();
                                    Toast.makeText(MainActivity.this, "uploaded!", Toast.LENGTH_SHORT).show();

                                }

                                @Override
                                public void onFailure(Call<String> call, Throwable t) {
                                    Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
                                }
                            });
                }
            }).start();

I need to cancel the call in onResponse from outside the Thread via a progressDialog.setButton(). How is this possible?

Any help is Appreciated!


Solution

  • You need to get instance of mService.uploadFile(body). This is retrofit2.Call<T> interface with public method cancel().

       ...{
        call = mService.uploadFile(body)
        call.enqueue(new Callback<String>() {
       ...
    

    And use it like this

      void cancel() {
            if (!call.isCanceled && call.isExecuted) call.cancel()
        }
    

    Also metohd enqueue(Callback<T> callback)

    Asynchronously send the request and notify callback of its response or if an error occurred talking to the server, creating the request, or processing the response.

    You don't need to use Thread() to deal with it.