Quantcast
Channel: Yudiz Solutions Ltd.
Viewing all articles
Browse latest Browse all 595

Kotlin : Android’s future is here – Part 5

$
0
0

Overview

Retrofit

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:-

compile "com.squareup.retrofit2:retrofit:2.3.0"
compile "com.squareup.retrofit2:adapter-rxjava2:2.3.0"
compile "com.squareup.retrofit2:converter-gson:2.3.0"
compile "io.reactivex.rxjava2:rxandroid:2.0.1"

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,

data class User(
        val login: String,
        val id: Long,
        val url: String,
        val html_url: String,
        val followers_url: String,
        val following_url: String,
        val starred_url: String,
        val gists_url: String,
        val type: String
)

data class Result(val total_count: Int, val incomplete_results: Boolean, val items: List<User>)

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:

interface GithubApiService {
    @GET("search/users")
    fun search(@Query("q") query: String): Observable<Result>
}

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.

val retrofit = Retrofit.Builder()               .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
                .baseUrl("https://api.github.com/")
                .build()

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.

val apiInterface = retrofit.create(GithubApiService::class.java)

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

apiInterface.search("Java")
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe({

                    result ->
                    Log.d("Result", "${result.total_count} results found")
                }, { error ->
                    error.printStackTrace()
                })

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.

Conclusion

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.


Viewing all articles
Browse latest Browse all 595

Trending Articles