Android Networking in 2019 — Retrofit with Kotlin’s Coroutines

Android Networking in 2019 — Retrofit with Kotlin’s CoroutinesNavendra JhaBlockedUnblockFollowFollowingJan 13The year 2018 saw a lot of big changes in the Android World, especially in terms of Android Networking.

The launch of a stable version of Kotlin Coroutines fueled a lot of movement from RxJava to Kotlin Coroutines for handling multithreading in Android.

In this article, we will be talking about making Networking API calls in Android using Retrofit2 and Kotlin Coroutines.

We will be making a networking call to TMDB API to fetch popular movies.

I know all these concepts, Show me the code!!If you are experienced with Android Networking and have made networking calls before using Retrofit but probably with other libraries viz RxJava, instead of Kotlin Coroutines and just want to check out the implementation, check out this code readme on Github.

Android Networking in NutshellIn a nutshell, android networking or any networking works in the following way:Request— Make an HTTP request to an URL (called as endpoint) with proper headers generally with Authorisation Key if required.

Response — The Request will return a response which can be error or success.

In the case of success, the response will contain the contents of the endpoint (generally they are in JSON format)Parse & Store — We will parse this JSON and get the required values and store them in our data class.

In Android, we use —Okhttp — For creating an HTTP request with all the proper headers.

Retrofit — For making the requestMoshi / GSON — For parsing the JSON dataKotlin Coroutines — For making non-blocking (main thread) network requests.

Picasso / Glide— For downloading an image from the internet and setting it into an ImageView.

Obviously, these are just some of the popular libraries but there are others too.

Also, most of these libraries are developed by awesome folks at Square Inc.

Check out this for more open source project by the Square Team.

Let's get startedThe Movie Database (TMDb) API contains a list of all popular, upcoming, latest, now showing movies and tv shows.

This is one of the most popular API to play with too.

TMDB API requires an API key to make requests.

For that:-Make an account at TMDBFollow steps described here to register for an API key.

Hiding API key in Version Control (Optional but Recommended)Once you have the API key, do the following steps to hide it in VCS.

Add your key in local.

properties present in the root folder.

Get access to the key in build.

gradle programmatically.

Then the key is available to you in the program though BuildConfig.

Setting up the ProjectFor setting up the project, we will first add all the required dependencies in build.

gradle (Module: app):-Now let’s create our TmdbAPI serviceLet’s see what we are doing here in ApiFactory.


First, we are creating a Network Interceptor to add api_key in all the request as authInterceptor.

Then we are creating a networking client using OkHttp and add our authInterceptor.

Next, we join everything together to create our HTML Request builder and handler using Retrofit.

Here we add our previously created networking client, base URL, and add a converter and an adapter factory.

 First is MoshiConverter which assist in JSON parsing and converts Response JSON into Kotlin data class with selective parsing if required.

The second one is CoroutineCallAdaptor which is aRetrofit2 CallAdapter.

Factory for Kotlin coroutine's Deferred.

Finally, we simply create our tmdbApi by passing a reference of TmdbApi class (This is created in the next section)to the previously created retrofit class.

Exploring the Tmdb APIWe get the following response for /movie/popular endpoint.

The response returns results which is array of movie object.

This is point of interest for us.

So now let’s create our Movie data class and MovieResponse class as per the json.

TmdbApi interfaceAfter creating data classes, we create TmdbApi interface whose reference we added in the retrofit builder in the earlier section.

In this interface, we add all the required API calls with any query parameter if necessary.

For example, for getting a movie by id we will add the following method to our interface:interface TmdbApi{ @GET("movie/popular") fun getPopularMovies() : Deferred<Response<TmdbMovieResponse>> @GET("movie/{id}") fun getMovieById(@Path("id") id:Int): Deferred<Response<Movie>>}Finally making a Networking CallNext, we finally make a networking call to get the required data, we can make this call in DataRepository or in ViewModel or directly in Activity too.

val movieService = ApiFactory.

tmdbApiGlobalScope .


Main) { val popularMovieRequest = movieService.

getPopularMovie() try { val response = popularMovieRequest.

await() if(response.

isSuccessful){ val movieResponse = response.

body() //This is single object Tmdb Movie response val popularMovies = movieResponse?.

results }else{ Log.

d("FetchMovie", response.


toString()) } }catch (e: Exception){ } }This is a basic introductory level but full production level API calls on Android.

For more examples, visit here.

Happy Coding!.

. More details

Leave a Reply