AndroidPub
Published in

AndroidPub

Android Networking in 2019 — Retrofit with Kotlin’s Coroutines

The 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, checkout github page for the same:

Android Networking in Nutshell

In 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 request
  • Moshi / GSON — For parsing the JSON data
  • Kotlin 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 started

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

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 Project

For setting up the project, we will first add all the required dependencies in build.gradle (Module: app):-

Now let’s create our TmdbAPI service

Let’s see what we are doing here in ApiFactory.kt.

  • 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 HTTP 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 API

We get the following response for /movie/popular endpoint. The response returns results which is an array of movie object. This is a point of interest for us.

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

TmdbApi interface
After 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 Call

Next, 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.

Sealed Result Class

Class to handle Network response. It either can be Success with the required data or Error with an exception.

Building BaseRepository to handle safeApiCall

Building MovieRepository

Creating the View Model to fetch data

Using ViewModel in Activity to Update UI

This is a basic introductory but full production level API calls on Android. For more examples, visit here.

Happy Coding!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store