Kotlin : Android’s future is here – Part 5



In this blog, we will concentrate on very important aspect in Android – API integration.
We will use Retrofit library in this demo and the response of the API is observed using RxJava.
Let’s get started.

Including libraries in gradle file:

After configuring Kotlin in the project, we will need 4 libraries:-

Making model to store data:

We will use GitHub API – https://api.github.com/search/users.
So the model class according to its response will be,

Make a class called Results and include data as mentioned above.
data keyword specifies that this class is supposed to hold data and such classes automatically override functions like toString( ) and hashCode( ).

Making interface to interact with the API from our project:

As shown above, I have used @GET annotation as the API uses GET method with parameters:- q for query and few other optional parameters like page and per_page for pagination purpose.

We can also see search/users as parameter of @GET annotation. It is the url that attaches with base url which is https://api.github.com/.

There is a method called search( ) which takes parameters (query) as the argument and returns Observable. Observable is from RxJava which stores the result if response is obtained successfully otherwise it displays the error.

Note:- Here, we are aiming to get response from GitHub by passing Java as our query

Calling API and obtaining response:

In MainActivity.kt, build the retrofit object as shown below.

Here, we have used GsonConverterFactory with retrofit and we also have to add CallAdapterFactory as we are using RxJava. This factory will enable us to use functions like observeOn, subscribeOn, subscribe etc. which are used to get the response stored in Observable in proper way.

Now, create an instance of the interface using retrofit.

Using this variable, we can access the function defined in interface.

Here, we have passed Java as the argument.

ObserveOn( ) will be used to access main thread of the app and manage changes made to the UI of app as the API is called (if required).
SubscribeOn( ) will work in back-end on another thread which is used to call the API.
With subscribe( ), we can obtain result of the response.

D/Result: 30895 results found
Here, we have obtained the above result in the console.


API integration is another very important topic in Android World and out of many ways to achieve this integration, Retrofit is the best in my opinion.

Kotlin encourages to use RxJava along with retrofit. This will help us to receive the response of API in proper way than the usual way i.e. by AsyncTask.


Sumeet Rukeja Android Developer

I am an Android Developer at Yudiz Solutions Pvt. Ltd. - a leading Mobile App Development Company. I am passionate about developing android apps and to learn more and more about the deep sea of Android.

Leave a Reply