Written by Adrian Kremski
Android Developer
Published October 8, 2015

Retrofit 2.0: what’s new?

Retrofit is a HTTP client library for Android created by Square. In this post we will cover the new version of Retrofit introduced by Jack Wharton during Droidcon NYC 2015 and what has changed in it.

For purpose of presenting Retrofit 2.0 functions we are going to work with API created on apiary.io platform.

Let’s get down to business!

1. Setup

First, we will add a few dependencies to our gradle.build to fetch Retrofit and corresponding tools.

Retrofit 2.0 beta

Gson converter

In Retrofit 1.9, GsonConverter was a default option for the RestAdapter but from now on the converters need to be plugged in manually.

Other converters

2. API

After gradle setup, let’s dig into the API with which we are going to communicate.

Our “backend” serves 3 urls

[GET] http://private-1ab0-adriankremski.apiary-mock.com/notes for fetching notes

[POST] http://private-1ab0-adriankremski.apiary-mock.com/notes for creating new notes

[GET] http://private-1ab0-adriankremski.apiary-mock.com/notes/{id}

Now that we know, what our resource looks like we can define the Note model in Java

Pretty simple, isn’t it ?

3. NotesService

All API endpoints must be mapped to a corresponding interfaces in Java, so let’s do this

Retrofit 2.0 introduced a new Call class (it also exists in OkHttp package).

Screen Shot 2015-10-06 at 15.44.27

(screen is taken from Jack Whartons presentation during Droidcon NYC 2015, available here)

Similar endpoints that can be defined in Java with Retrofit

After defining the NotesService we can finally make some requests.
To do that we will use the Retrofit class (in 1.9 it’s called RestAdapter) to instantiate our NotesService.

Now we have two options to do HTTP calls.

Synchronous and asynchronous

As you can see we have two methods to handle here: onResponse and onFailure.

If the request is successful, onResponse method is called with the response encapsulated in the response variable. In case of a failure, both methods are invoked, (response.body() will return as null but you can retrieve the error body from response.errorBody()).

Overview of the Response class

Remember that each Call instance can be invoked only once. Otherwise it will throw an exception

If we want to retry the call, we can clone it and then execute

4. Integrating RxJava

Retrofit 1.9 allowed developers to use RxJava for requests invocation. In v2.0 it’s still possible, however it requires some extra steps.

To integrate it, we need a custom CallAdapter mechanism (already available in Retrofit)

Updating retrofit instance

Finally, we are ready to integrate Observables with our NotesService

5. Final note

For more changes, please check the Changelog of Retrofit 2.0 and official documentation available  here

Written by Adrian Kremski
Android Developer
Published October 8, 2015