Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cancel ongoing request in retrofit when retrofit.client.UrlConnectionClient is used as client?

I am using retrofit for http calls in my Android application and retrofit.client.UrlConnectionClient as the client while building the adapter.

RestAdapter.Builder builder = new RestAdapter.Builder()
            .setEndpoint(url)
            .setLogLevel(RestAdapter.LogLevel.FULL)
            .setClient(
                    new Client.Provider() {
                        public Client get() {
                            return new UrlConnectionClient() {
                                @Override
                                protected HttpURLConnection openConnection(Request request)
                                        throws IOException {
                                    HttpURLConnection connection = super.openConnection(request);
                                    connection.setConnectTimeout(connectionTimeout);
                                    return connection;
                                }

I wanted to set the timeout so I have used UrlConnectionClient as my client. I could not find a way with other clients like OkHttp.

Question is : How can I cancel the ongoing request ?.

I have seen a similar post @ Using Square's Retrofit Client, is it possible to cancel an in progress request? If so how? but my code would get really complex if I try to add my own executors and try to cancel the request using that. I am looking if there is slightly a better way with my existing code.

I also see that Retorofit V2.0 has plan for Retry and Cancel but not sure when that would be released..https://github.com/square/retrofit/issues/297

Need help ! In fact I also need a way to retry with the same code.

like image 287
cgr Avatar asked Nov 01 '22 03:11

cgr


1 Answers

This has been available since 2.0.0-beta2 (https://github.com/square/retrofit/releases/tag/parent-2.0.0-beta2). I don't know if there is a doc that explains that but here is the link to API:
http://square.github.io/retrofit/2.x/retrofit/retrofit/Call.html#cancel--

'Call' API allows to do Retry as well by 'Clone'ing the request.

like image 84
cgr Avatar answered Nov 15 '22 05:11

cgr