In building the Android apps, Retrofit is the most popular for networking API call. It is very simple and cleaner way API call in the Android application. Retrofit used OkHttp request call which is extended and customized of Http request. It gives much better performance in comparison with another library like Volley.
Android developers love this because it is pretty simple and easy to integrate into an android application. Retrofit is not only simple to integrate but also provide many features like handling multiple requests, caching, and easy to handle the error. Great 🙂
I explained in one of my tutorial blogs about how to use retrofit in Android. I recommended to checking this post Retrofit with RxAndroid.
In this tutorial, we will learn how to use the retrofit API call in Kotlin by using RxJava and RxAndroid. Retrofit works very seamlessly with RxJava. RxAndroid provides the Android Scheduler for scheduling the main thread switch between the threads easily. Let’s see how to integrate Retrofit in Kotlin?
In the first step, we need to add Retrofit, RxJava, and RxAndroid dependencies into a build.gradle file in app level. Here are dependencies.
// RX rxjava2_version: 2.0.1 compile "io.reactivex.rxjava2:rxjava:$rxjava2_version" compile "io.reactivex.rxjava2:rxandroid:$rxjava2_version" // Retrofit + GSON + Interceptor retrofit_version = 2.2.0 compile "com.squareup.retrofit2:retrofit:$retrofit_version" compile "com.squareup.retrofit2:adapter-rxjava2:$retrofit_version" compile "com.squareup.retrofit2:converter-gson:$retrofit_version" compile 'com.squareup.okhttp3:logging-interceptor:3.6.0'
Now we need to create the ApiService class to retrofit initialized.
/** * Created by sunil on 5/30/2017. */class ApiService { val service : ApiServiceInterface var baseUrl = "http://demo2974937.mockable.io/" init { val logging = HttpLoggingInterceptor() logging.level = HttpLoggingInterceptor.Level.BODY val httpClient = OkHttpClient.Builder() httpClient.addInterceptor(logging) val gson = GsonBuilder() .setLenient() .create() val retrofit = Retrofit.Builder() .baseUrl(baseUrl) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create(gson)) .client(httpClient.build()) .build() service = retrofit.create<ApiServiceInterface>(ApiServiceInterface::class.java) } fun loadFriends(): Observable<Friends> { return service.getMyFriends() } }
Here is the sample JSON model.
{ "user": [{ "id": "1", "name": "Raj Amal", "email": "raj.amalw@gmail.com" },{ "id": "2", "name": "sunil", "email": "sunil@gmail.com" },{ "id": "3", "name": "Awadhesh", "email": "awadesh@gmail.com" },{ "id": "4", "name": "Sandy", "email": "sandy@gmail.com" },{ "id": "5", "name": "Jitendra", "email": "jda@gmail.com" }] }
We need to create the ApiServiceInterface for post and query for networking and model class or POJO for parsing JSON into a plain Java class.
class Friends { @SerializedName("user") @Expose var user: List<User>? = null class User { @SerializedName("id") @Expose var id: String? = null @SerializedName("name") @Expose var name: String? = null @SerializedName("email") @Expose var email: String? = null constructor(id: String, name: String, email: String) } }
Here is ApiServiceInterface class.
interface ApiServiceInterface { @GET("getmyfriends") fun getMyFriends(): Observable<Friends> }
Now the API call for networking by using Retrofit is ready now. Ohh that’s pretty simple right 🙂
Ok Now my target is not only to create and initialized retrofit but also want to show a demo to fetch some data from mockable io server. Once I fetched data from server lets shows those data into RecyclerView. Here I am calling retrofit.
// call retrofit presenter.loadFriendsAPI();
I have implemented this into presenter class. Here is detail.
override fun loadFriendsAPI() { getFriends(true) }
fun getFriends(isSubcribes : Boolean){ if (isSubcribes) { var observableFriends = ApiService().loadFriends() updateView(observableFriends, true) } }
Retrofit help us for parsing data in a very simple way using Gson Library. Now we got the Observable<Friends> data to do on next to show on View.
fun updateView( observableFriends: Observable<Friends>, isAPI : Boolean){ var subscribe = observableFriends.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({friends: Friends? -> if (isAPI){ // insert into db var listUsers = friends!!.user; listUsers?.let { for (users in it) { DbManager().saveFriendsList(users) } } view.onLoadFriendsOk(listUsers!!)}}, { t: Throwable? -> view.showEmptyView(true)}) subscriptions.add(subscribe) } }
Now we can load this data into recycler view. I used recycler view in FriendsListFragment class.
override fun onLoadFriendsOk(friends: List<Friends.User>) { // Here you can get data ans show on UI var adapter = FriendsAdapter(activity, friends.toMutableList(), this); recyclerView!!.setLayoutManager(LinearLayoutManager(activity)) recyclerView!!.setAdapter(adapter) }
Wrapping Up: As we practiced that retrofit is very simple and easy to integrate into Android for building awesome Android apps. We can do a lot with retrofit and Reactive Rx. You can play with more to add more features.
Here is the Github link of source code.
In my next tutorial, we can learn how to use Anko Db with a retrofit for offline data sync in Kotlin. If you want to learn basic concepts of Kotlin then I recommended to checking all post here Basic of Kotlin get started in Android part- 1, part -2, part -3 and part -4. Great 🙂
Please do subscribe your email to get every newsletter from this blog and if you feel that this post helps you then do not forget to share and comment below.
Happy Coding 🙂
I am a very enthusiastic Android developer to build solid Android apps. I have a keen interest in developing for Android and have published apps to the Google Play Store. I always open to learning new technologies. For any help drop us a line anytime at contact@mobologicplus.com
Hi everyone, In this article, we are going to learn how to hide the production… Read More
Hello everyone, Today in this article, we are going to learn about localisation to support… Read More
Hello everyone, In this article, we are going to learn something to handle the callback… Read More
In this article, we are learning about the run time permissions for request permission launchers.… Read More
Hello everyone. In my last tutorial, we learned about the Jetpack Compose introduction and about applying the… Read More
Hello everyone, In this article, we are going to learn about the Jetpack Compose with… Read More