Kriptofolio app series – Part 5: Handle RESTful Web Services using Retrofit, OkHttp, Gson, Glide and Coroutines

These days almost every Android app connects to internet to get/send data. You should definitely need to learn how to handle RESTful Web Services as their correct implementation is the core knowledge while creating modern app. This part is going to be complicated. We are going to combine multiple libraries at once to get working result. I am not going to talk about native Android way how to handle internet requests, because in real world nobody use it. Every good app does not try to reinvent the wheel but instead use the most popular third party libraries to solve common problems. It would be too much complicated to recreate the functionality that these well made libraries has to offer.

Series content

What is Retrofit, OkHttp and Gson?

Retrofit is a REST Client for Java and Android. This library in my opinion is the most important one to learn, as it will do the main job. It makes it relatively easy to retrieve and upload JSON (or other structured data) via a REST based webservice. In Retrofit you configure which converter is used for the data serialization. Typically to serialize and deserialize objects to and from JSON you use an open-source Java library – Gson. Also if you need, you can add custom converters to Retrofit to process XML or other protocols. For making HTTP requests Retrofit uses the OkHttp library. OkHttp is a pure HTTP/SPDY client responsible for any low-level network operations, caching, requests and responses manipulation. In contrast, Retrofit is a high-level REST abstraction build on top of OkHttp. Retrofit is strongly coupled with OkHttp and makes intensive use of it.

Now as you know that everything is closely related, we are going to use all these 3 libraries at once. Our first goal is to get all the cryptocurrencies list using Retrofit from the Internet. We will use special OkHttp interceptor class for CoinMarketCap API authentication when making a call to the server. We will get back a JSON data result and than convert it using Gson library.

Quick setup for Retrofit 2 just to try it first

When learning something new I like to try it practically as soon as I can. We will apply similar approach with Retrofit 2 for you to understand it better quickly. Don’t worry right now about code quality, any programming principles or optimizations, just write some code to make Retrofit 2 work in our project and discuss what it does.

Follow these steps to setup Retrofit 2 on My Crypto Coins app project:

      1. For the start you should give INTERNET permission for the app.

        It’s obvious that we are going to execute HTTP requests on a server accessible via the Internet. Give this permission by adding these lines to your Manifest file:

        <manifest xmlns:android=""
            <uses-permission android:name="android.permission.INTERNET" />
      2. Than you should add library dependencies.

        Find out latest Retrofit version. Also you should know that Retrofit doesn’t ship with an integrated JSON converter. Because we will get response as JSON format, we need to include the converter manually in the dependencies too. We are going to use latest Google’s JSON converter Gson version. Let’s add these lines to your gradle file:

        // 3rd party
        // HTTP client - Retrofit with OkHttp
        implementation "com.squareup.retrofit2:retrofit:$versions.retrofit"
        // JSON converter Gson for JSON to Java object mapping
        implementation "com.squareup.retrofit2:converter-gson:$versions.retrofit"

        As you noticed from my comment OkHttp dependency is already shipped with Retrofit 2 dependency. Versions is just separate gradle file for convenience:

        def versions = [:]
        versions.retrofit = "2.4.0"
        ext.versions = versions
      3. Next set up the Retrofit interface.

        It’s an interface that declares our requests and their types. Here we define API on the client side.

         * REST API access points.
        interface ApiService {
            // The @GET annotation tells retrofit that this request is a get type request.
            // The string value tells retrofit that the path of this request is
            // baseUrl + v1/cryptocurrency/listings/latest + query parameter.
            // Annotation @Query is used to define query parameter for request. Finally the request url will
            // look like that
            fun getAllCryptocurrencies(@Query("convert") currency: String): Call<CryptocurrenciesLatest>
            // The return type for this function is Call with its type CryptocurrenciesLatest.
      4. And set up data class.

        Data classes are POJOs (Plain Old Java Objects) that represents the responses of the API calls which we’re going to make.

         * Data class to handle the response from the server.
        data class CryptocurrenciesLatest(
                val status: Status,
                val data: List<Data>
        ) {
            data class Data(
                    val id: Int,
                    val name: String,
                    val symbol: String,
                    val slug: String,
                    // The annotation to a model property lets you pass the serialized and deserialized
                    // name as a string. This is useful if you don't want your model class and the JSON
                    // to have identical naming.
                    val circulatingSupply: Double,
                    val totalSupply: Double,
                    val maxSupply: Double,
                    val dateAdded: String,
                    val numMarketPairs: Int,
                    val cmcRank: Int,
                    val lastUpdated: String,
                    val quote: Quote
            ) {
                data class Quote(
                        // For additional option during deserialization you can specify value or alternative
                        // values. Gson will check the JSON for all names we specify and try to find one to
                        // map it to the annotated property.
                        @SerializedName(value = "USD", alternate = ["AUD", "BRL", "CAD", "CHF", "CLP",
                            "CNY", "CZK", "DKK", "EUR", "GBP", "HKD", "HUF", "IDR", "ILS", "INR", "JPY",
                            "KRW", "MXN", "MYR", "NOK", "NZD", "PHP", "PKR", "PLN", "RUB", "SEK", "SGD",
                            "THB", "TRY", "TWD", "ZAR"])
                        val currency: Currency
                ) {
                    data class Currency(
                            val price: Double,
                            val volume24h: Double,
                            val percentChange1h: Double,
                            val percentChange24h: Double,
                            val percentChange7d: Double,
                            val marketCap: Double,
                            val lastUpdated: String
            data class Status(
                    val timestamp: String,
                    val errorCode: Int,
                    val errorMessage: String,
                    val elapsed: Int,
                    val creditCount: Int
      5. Create special interceptor class for authentication when making a call to the server.

        This is the case particular for any API that requires authentication to get successful response. Interceptors are a powerful way to customize your requests. We are going to intercept the actual request and to add individual request header, which will validate the call with an API Key provided by CoinMarketCap Professional API Developer Portal. To get yours, you need to register there.

         * Interceptor used to intercept the actual request and
         * to supply your API Key in REST API calls via a custom header.
        class AuthenticationInterceptor : Interceptor {
            override fun intercept(chain: Interceptor.Chain): Response {
                val newRequest = chain.request().newBuilder()
                        // TODO: Use your API Key provided by CoinMarketCap Professional API Developer Portal.
                        .addHeader("X-CMC_PRO_API_KEY", "CMC_PRO_API_KEY")
                return chain.proceed(newRequest)
      6. Finally we will add this code to our activity to see Retrofit working.

        As I want to get your hands dirty as soon as possible, so I placed everything in one place. This is not the correct way but the fastest one instead just to see visual result quickly.

        class AddSearchActivity : AppCompatActivity(), Injectable {
            private lateinit var listView: ListView
            private lateinit var listAdapter: AddSearchListAdapter
            override fun onCreate(savedInstanceState: Bundle?) {
                // Later we will setup Retrofit correctly, but for now we do all in one place just for quick start.
            private fun setupRetrofitTemporarily() {
                // We need to prepare a custom OkHttp client because need to use our custom call interceptor.
                // to be able to authenticate our requests.
                val builder = OkHttpClient.Builder()
                // We add the interceptor to OkHttpClient.
                // It will add authentication headers to every call we make.
                val client =
                val api = Retrofit.Builder() // Create retrofit builder.
                        .baseUrl("") // Base url for the api has to end with a slash.
                        .addConverterFactory(GsonConverterFactory.create()) // Use GSON converter for JSON to POJO object mapping.
                        .client(client) // Here we set the custom OkHttp client we just created.
                        .build().create( // We create an API using the interface we defined.
                val adapterData: MutableList<Cryptocurrency> = ArrayList<Cryptocurrency>()
                val currentFiatCurrencyCode = "EUR"
                // Let's make asynchronous network request to get all latest cryptocurrencies from the server.
                // For query parameter we pass "EUR" as we want to get prices in euros.
                val call = api.getAllCryptocurrencies("EUR")
                val result = call.enqueue(object : Callback<CryptocurrenciesLatest> {
                    // You will always get a response even if something wrong went from the server.
                    override fun onFailure(call: Call<CryptocurrenciesLatest>, t: Throwable) {
                                // Throwable will let us find the error if the call failed.
                                "Call failed! " + t.localizedMessage,
                    override fun onResponse(call: Call<CryptocurrenciesLatest>, response: Response<CryptocurrenciesLatest>) {
                        // Check if the response is successful, which means the request was successfully
                        // received, understood, accepted and returned code in range [200..300).
                        if (response.isSuccessful) {
                            // If everything is OK, let the user know that.
                            Toast.makeText(this@AddSearchActivity, "Call OK.", Toast.LENGTH_LONG).show();
                            // Than quickly map server response data to the ListView adapter.
                            val cryptocurrenciesLatest: CryptocurrenciesLatest? = response.body()
                            cryptocurrenciesLatest!!.data.forEach {
                                val cryptocurrency = Cryptocurrency(, it.cmcRank.toShort(),
                                        0.0, it.symbol, currentFiatCurrencyCode, it.quote.currency.price,
                                        0.0, it.quote.currency.percentChange1h,
                                        it.quote.currency.percentChange7d, it.quote.currency.percentChange24h,
                            listView.visibility = View.VISIBLE
                        // Else if the response is unsuccessful it will be defined by some special HTTP
                        // error code, which we can show for the user.
                        else Snackbar.make(findViewById(,
                                "Call error with HTTP status code " + response.code() + "!",

        You can explore the code here. Remember this is only initial simplified implementation version for you to get the idea better.

Final correct setup for Retrofit 2 with OkHttp 3 and Gson

Ok after quick experiments it is time to bring this Retrofit implementation to the next level. We already got the data successfully but not correctly. We are missing the state like loading, error and success. Our code is mixed without separation of concerns. It’s a common mistake to write all your code in an activity or a fragment. Our activity class is UI based and should only contain logic that handles UI and operating system interactions. Actually after this quick setup I worked a lot and made many changes. There is no point to put all the code that was changed in the article. Better instead you should browse final Part 5 code repo here. I have commented everything very well and my code should be clear for you to understand. But I am going to talk about most important things I have done and why I did that.

First step to improve was to start using Dependency Injection. Remember from the previous part we already have Dagger 2 implemented inside the project correctly. So I used it for Retrofit setup.

 * AppModule will provide app-wide dependencies for a part of the application.
 * It should initialize objects used across our application, such as Room database, Retrofit, Shared Preference, etc.
@Module(includes = [ViewModelsModule::class])
class AppModule() {

    fun provideHttpClient(): OkHttpClient {
        // We need to prepare a custom OkHttp client because need to use our custom call interceptor.
        // to be able to authenticate our requests.
        val builder = OkHttpClient.Builder()
        // We add the interceptor to OkHttpClient.
        // It will add authentication headers to every call we make.

        // Configure this client not to retry when a connectivity problem is encountered.

        // Log requests and responses.
        // Add logging as the last interceptor, because this will also log the information which
        // you added or manipulated with previous interceptors to your request.
        builder.interceptors().add(HttpLoggingInterceptor().apply {
            // For production environment to enhance apps performance we will be skipping any
            // logging operation. We will show logs just for debug builds.
            level = if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE

    fun provideApiService(httpClient: OkHttpClient): ApiService {
        return Retrofit.Builder() // Create retrofit builder.
                .baseUrl(API_SERVICE_BASE_URL) // Base url for the api has to end with a slash.
                .addConverterFactory(GsonConverterFactory.create()) // Use GSON converter for JSON to POJO object mapping.
                .client(httpClient) // Here we set the custom OkHttp client we just created.
                .build().create( // We create an API using the interface we defined.


Now as you see Retrofit is separated from activity class as it should be. It will be initialized only once and used app wide.

As you may noticed while creating Retrofit builder instance we add special Retrofit calls adapter using addCallAdapterFactory. By default Retrofit returns a Call<T> but for our project we require it to return LiveData<T> type. In order to do that we need to add LiveDataCallAdapter by using LiveDataCallAdapterFactory.

 * A Retrofit adapter that converts the Call into a LiveData of ApiResponse.
 * @param <R>
</R> */
class LiveDataCallAdapter<R>(private val responseType: Type) :
        CallAdapter<R, LiveData<ApiResponse<R>>> {

    override fun responseType() = responseType

    override fun adapt(call: Call<R>): LiveData<ApiResponse<R>> {
        return object : LiveData<ApiResponse<R>>() {
            private var started = AtomicBoolean(false)
            override fun onActive() {
                if (started.compareAndSet(false, true)) {
                    call.enqueue(object : Callback<R> {
                        override fun onResponse(call: Call<R>, response: Response<R>) {

                        override fun onFailure(call: Call<R>, throwable: Throwable) {
class LiveDataCallAdapterFactory : CallAdapter.Factory() {
    override fun get(
            returnType: Type,
            annotations: Array<Annotation>,
            retrofit: Retrofit
    ): CallAdapter<*, *>? {
        if (CallAdapter.Factory.getRawType(returnType) != {
            return null
        val observableType = CallAdapter.Factory.getParameterUpperBound(0, returnType as ParameterizedType)
        val rawObservableType = CallAdapter.Factory.getRawType(observableType)
        if (rawObservableType != {
            throw IllegalArgumentException("type must be a resource")
        if (observableType !is ParameterizedType) {
            throw IllegalArgumentException("resource must be parameterized")
        val bodyType = CallAdapter.Factory.getParameterUpperBound(0, observableType)
        return LiveDataCallAdapter<Any>(bodyType)

Now we will get LiveData<T> instead of Call<T> as return type from Retrofit service methods defined in ApiService interface.

Another important step to make is to start using Repository pattern. I have talked about it in Part 3. Check our MVVM architecture schema from that post to remember where it goes.

As you see in the picture Repository is a separate layer for the data. Its our single source of contact for getting or sending data. When we use Repository we are following separation of concerns principle. We can have different data sources like in our case persistent data from SQLite database and data from web services, but Repository is always going to be single source of truth for all app data. Instead of communicating with our Retrofit implementation directly we are going to use Repository for that. For each kind of entity we are going to have separate Repository.

 * The class for managing multiple data sources.
class CryptocurrencyRepository @Inject constructor(
        private val context: Context,
        private val appExecutors: AppExecutors,
        private val myCryptocurrencyDao: MyCryptocurrencyDao,
        private val cryptocurrencyDao: CryptocurrencyDao,
        private val api: ApiService,
        private val sharedPreferences: SharedPreferences
) {

    // Just a simple helper variable to store selected fiat currency code during app lifecycle.
    // It is needed for main screen currency spinner. We set it to be same as in shared preferences.
    var selectedFiatCurrencyCode: String = getCurrentFiatCurrencyCode()


    // The Resource wrapping of LiveData is useful to update the UI based upon the state.
    fun getAllCryptocurrencyLiveDataResourceList(fiatCurrencyCode: String, shouldFetch: Boolean = false, callDelay: Long = 0): LiveData<Resource<List<Cryptocurrency>>> {
        return object : NetworkBoundResource<List<Cryptocurrency>, CoinMarketCap<List<CryptocurrencyLatest>>>(appExecutors) {

            // Here we save the data fetched from web-service.
            override fun saveCallResult(item: CoinMarketCap<List<CryptocurrencyLatest>>) {

                val list = getCryptocurrencyListFromResponse(fiatCurrencyCode,, item.status?.timestamp)


            // Returns boolean indicating if to fetch data from web or not, true means fetch the data from web.
            override fun shouldFetch(data: List<Cryptocurrency>?): Boolean {
                return data == null || shouldFetch

            override fun fetchDelayMillis(): Long {
                return callDelay

            // Contains the logic to get data from the Room database.
            override fun loadFromDb(): LiveData<List<Cryptocurrency>> {

                return Transformations.switchMap(cryptocurrencyDao.getAllCryptocurrencyLiveDataList()) { data ->
                    if (data.isEmpty()) {
                    } else {

            // Contains the logic to get data from web-service using Retrofit.
            override fun createCall(): LiveData<ApiResponse<CoinMarketCap<List<CryptocurrencyLatest>>>> = api.getAllCryptocurrencies(fiatCurrencyCode)



    fun getCurrentFiatCurrencyCode(): String {
        return sharedPreferences.getString(context.resources.getString(R.string.pref_fiat_currency_key), context.resources.getString(R.string.pref_default_fiat_currency_value))
                ?: context.resources.getString(R.string.pref_default_fiat_currency_value)


    private fun getCryptocurrencyListFromResponse(fiatCurrencyCode: String, responseList: List<CryptocurrencyLatest>?, timestamp: Date?): ArrayList<Cryptocurrency> {

        val cryptocurrencyList: MutableList<Cryptocurrency> = ArrayList()

        responseList?.forEach {
            val cryptocurrency = Cryptocurrency(,, it.cmcRank.toShort(),
                    it.symbol, fiatCurrencyCode, it.quote.currency.price,
                    it.quote.currency.percentChange7d, it.quote.currency.percentChange24h, timestamp)

        return cryptocurrencyList as ArrayList<Cryptocurrency>


As you notice in CryptocurrencyRepository class code I am using NetworkBoundResource abstract class. What is it and why we need it? NetworkBoundResource is a small but very important helper class that will allow us to maintain a synchronization between local database and the web service. Our goal is to build modern application that would work smoothly even our device is offline. Also with the help of this class we will be able to present different network states like error or loading for the user visually. NetworkBoundResource starts by observing the database for the resource. When the entry is loaded from the database for the first time, it checks whether the result is good enough to be dispatched or that it should be re-fetched from the network. Note that both of these situations can happen at the same time, given that you probably want to show cached data while updating it from the network. If the network call completes successfully, it saves the response into the database and re-initializes the stream. If network request fails, the NetworkBoundResource dispatches a failure directly.

 * A generic class that can provide a resource backed by both the sqlite database and the network.
 * You can read more about it in the [Architecture
 * Guide](
 * @param <ResultType> - Type for the Resource data.
 * @param <RequestType> - Type for the API response.
</RequestType></ResultType> */

// It defines two type parameters, ResultType and RequestType,
// because the data type returned from the API might not match the data type used locally.
abstract class NetworkBoundResource<ResultType, RequestType>
@MainThread constructor(private val appExecutors: AppExecutors) {

    // The final result LiveData.
    private val result = MediatorLiveData<Resource<ResultType>>()

    init {
        // Send loading state to UI.
        result.value = Resource.loading(null)
        val dbSource = loadFromDb()
        result.addSource(dbSource) { data ->
            if (shouldFetch(data)) {
            } else {
                result.addSource(dbSource) { newData ->

    private fun setValue(newValue: Resource<ResultType>) {
        if (result.value != newValue) {
            result.value = newValue

    // Fetch the data from network and persist into DB and then send it back to UI.
    private fun fetchFromNetwork(dbSource: LiveData<ResultType>) {
        val apiResponse = createCall()
        // We re-attach dbSource as a new source, it will dispatch its latest value quickly.
        result.addSource(dbSource) { newData ->

        // Create inner function as we want to delay it.
        fun fetch() {
            result.addSource(apiResponse) { response ->
                when (response) {
                    is ApiSuccessResponse -> {
                        appExecutors.diskIO().execute {
                            appExecutors.mainThread().execute {
                                // We specially request a new live data,
                                // otherwise we will get immediately last cached value,
                                // which may not be updated with latest results received from network.
                                result.addSource(loadFromDb()) { newData ->
                    is ApiEmptyResponse -> {
                        appExecutors.mainThread().execute {
                            // reload from disk whatever we had
                            result.addSource(loadFromDb()) { newData ->
                    is ApiErrorResponse -> {
                        result.addSource(dbSource) { newData ->
                            setValue(Resource.error(response.errorMessage, newData))

        // Add delay before call if needed.
        val delay = fetchDelayMillis()
        if (delay > 0) {
            Handler().postDelayed({ fetch() }, delay)
        } else fetch()


    // Called when the fetch fails. The child class may want to reset components
    // like rate limiter.
    protected open fun onFetchFailed() {}

    // Returns a LiveData object that represents the resource that's implemented
    // in the base class.
    fun asLiveData() = result as LiveData<Resource<ResultType>>

    protected open fun processResponse(response: ApiSuccessResponse<RequestType>) = response.body

    // Called to save the result of the API response into the database.
    protected abstract fun saveCallResult(item: RequestType)

    // Called with the data in the database to decide whether to fetch
    // potentially updated data from the network.
    protected abstract fun shouldFetch(data: ResultType?): Boolean

    // Make a call to the server after some delay for better user experience.
    protected open fun fetchDelayMillis(): Long = 0

    // Called to get the cached data from the database.
    protected abstract fun loadFromDb(): LiveData<ResultType>

    // Called to create the API call.
    protected abstract fun createCall(): LiveData<ApiResponse<RequestType>>

Under the hood NetworkBoundResource class  is made by using MediatorLiveData and its ability to observe multiple LiveData sources at once. Here we have two LiveData sources – the database and the network call response. Both of those LiveData are wrapped into one MediatorLiveData which is exposed by NetworkBoundResource.


Lets take a closer look how the NetworkBoundResource will work in our app concrete case. Imagine the user will launch the app and click on floating action button on the bottom right corner. App will launch add crypto coins screen. Now we can analize NetworkBoundResource usage inside it. If app is freshly installed and it is its first launch, than there will not be any data inside local database stored.  Because there is no data to show, a loading progress bar UI will be shown. Meanwhile an app is going to make a request call to the server via web service to get all the cryptocurrencies list. If response is unsuccessful than error message UI will be shown with ability to retry a call by pressing a button. When a request call will be successful at last, than the response data will be saved to local SQLite database. If we come back to the same screen next time, the app will load data from database instead of making a call to internet again. But user can ask for new data update by implemented pull-to-refresh functionality. Old data information will be shown whilst the network call is happening. All this is done with the help of NetworkBoundResource.

Another class used in our Repository and LiveDataCallAdapter where all the “magic” happens is ApiResponse. Actually ApiResponse is just a simple common wrapper around the Retrofit2.Response class that convert each response to instance of LiveData.

 * Common class used by API responses. ApiResponse is a simple wrapper around the Retrofit2.Call
 * class that convert responses to instances of LiveData.
 * @param <CoinMarketCapType> the type of the response object
</T> */
@Suppress("unused") // T is used in extending classes
sealed class ApiResponse<CoinMarketCapType> {
    companion object {
        fun <CoinMarketCapType> create(error: Throwable): ApiErrorResponse<CoinMarketCapType> {
            return ApiErrorResponse(error.message ?: "Unknown error.")

        fun <CoinMarketCapType> create(response: Response<CoinMarketCapType>): ApiResponse<CoinMarketCapType> {
            return if (response.isSuccessful) {
                val body = response.body()
                if (body == null || response.code() == 204) {
                } else {
                    ApiSuccessResponse(body = body)
            } else {

                // Convert error response to JSON object.
                val gson = Gson()
                val type = object : TypeToken<CoinMarketCap<CoinMarketCapType>>() {}.type
                val errorResponse: CoinMarketCap<CoinMarketCapType> = gson.fromJson(response.errorBody()!!.charStream(), type)

                val msg = errorResponse.status?.errorMessage ?: errorResponse.message
                val errorMsg = if (msg.isNullOrEmpty()) {
                } else {
                ApiErrorResponse(errorMsg ?: "Unknown error.")

 * Separate class for HTTP 204 resposes so that we can make ApiSuccessResponse's body non-null.
class ApiEmptyResponse<CoinMarketCapType> : ApiResponse<CoinMarketCapType>()

data class ApiSuccessResponse<CoinMarketCapType>(val body: CoinMarketCapType) : ApiResponse<CoinMarketCapType>()

data class ApiErrorResponse<CoinMarketCapType>(val errorMessage: String) : ApiResponse<CoinMarketCapType>()

Inside this wrapper class if our response has error, we use Gson library to convert error to JSON object. However If response was successful than Gson converter for JSON to POJO object mapping is used. We already added it when creating retrofit builder instance with GsonConverterFactory inside Dagger AppModule function provideApiService.

Glide for image loading

What is Glide? Glide is a fast and efficient open source media management and image loading framework for Android that wraps media decoding, memory and disk caching, and resource pooling into a simple and easy to use interface. Glide’s primary focus is on making scrolling any kind of a list of images as smooth and fast as possible, but it is also effective for almost any case where you need to fetch, resize, and display a remote image.

Sounds like a complicated library which offers many useful features that you would not want to develop all by yourself. In My Crypto Coins app we have several list screens where we need to show multiple cryptocurrencies logos-pictures taken from internet at once and still ensure smooth scrolling experience for the user, so this library fits well our needs perfectly. Also this library is very popular one among Android developers.

Steps to setup Glide on My Crypto Coins app project:

    1. Declare dependencies

      Get the latest Glide version. Again versions is separate file versions.gradle for the project.

      // Glide
      implementation "com.github.bumptech.glide:glide:$versions.glide"
      kapt "com.github.bumptech.glide:compiler:$versions.glide"
      // Glide's OkHttp3 integration.
      implementation "com.github.bumptech.glide:okhttp3-integration:$versions.glide"+"@aar"

      Because we want to use a networking library OkHttp in our project for all network operations, we need to include the specific Glide integration for it instead of the default one. Also since Glide is going to perform a network requests to load images via the internet, we need to include the permission INTERNET in our AndroidManifest.xml file, but we already did that with Retrofit setup.

    2. Create AppGlideModule

      Glide v4, which we will be using, offers a generated API for Applications. It will use an annotation processor to generate an API that allows applications to extend Glide’s API and include components provided by integration libraries. For any app to access the generated Glide API we need to include an appropriately annotated AppGlideModule implementation. There can be only a single implementation of the generated API and only one AppGlideModule per application.

      Lets create a class extending AppGlideModule somewhere in your app project:

       * Glide v4 uses an annotation processor to generate an API that allows applications to access all
       * options in RequestBuilder, RequestOptions and any included integration libraries in a single
       * fluent API.
       * The generated API serves two purposes:
       * Integration libraries can extend Glide’s API with custom options.
       * Applications can extend Glide’s API by adding methods that bundle commonly used options.
       * Although both of these tasks can be accomplished by hand by writing custom subclasses of
       * RequestOptions, doing so is challenging and produces a less fluent API.
      class AppGlideModule : AppGlideModule()

      Even if our application is not changing any additional settings or implementing any methods in AppGlideModule, we still need to have its implementation to use Glide. You’re not required to implement any of the methods in AppGlideModule for the API to be generated. You can leave the class blank as long as it extends AppGlideModule and is annotated with @GlideModule.

    3. Use Glide generated API

      When using AppGlideModule applications can use the API by starting all loads with GlideApp.with(). This is the code how I have used Glide to load and show cryptocurrencies logos in add crypto coins screen all cryptocurrencies list.

      class AddSearchListAdapter(val context: Context, private val cryptocurrencyClickCallback: ((Cryptocurrency) -> Unit)?) : BaseAdapter() {
          override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
              val itemBinding: ActivityAddSearchListItemBinding
              // We make an Uri of image that we need to load. Every image unique name is its id.
              val imageUri = Uri.parse(CRYPTOCURRENCY_IMAGE_URL).buildUpon()
                      .appendPath( + CRYPTOCURRENCY_IMAGE_FILE)
              // Glide generated API from AppGlideModule.
                      // We need to provide context to make a call.
                      // Here you specify which image should be loaded by providing Uri.
                      // The way you combine and execute multiple transformations.
                      // WhiteBackground is our own implemented custom transformation.
                      // CircleCrop is default transformation that Glide ships with.
                      .transform(MultiTransformation(WhiteBackground(), CircleCrop()))
                      // The target ImageView your image is supposed to get displayed in.
              return itemBinding.root

As you see you can start using Glide with just few lines of code and let it do all the hard work for you. It is pretty straightforward.

Kotlin Coroutines

While building this app we are going to face situations when we will run time consuming tasks such as writing data to a database or reading from it, fetching data from the network and other. All these common tasks take longer time to complete than allowed by Android framework the main thread. The main thread is a single thread that handles all updates to the UI. Developers are required not to block it to avoid the app freeze or even crash with an Application Not Responding dialog. Kotlin coroutines is going to solve this problem for us by introducing main thread safety. It is the last missing piece that we want to add for My Crypto Coins app.

Coroutines are a Kotlin feature that convert async callbacks for long-running tasks, such as database or network access, into sequential code. With coroutines, you can write asynchronous code, which was traditionally written using the Callback pattern, using synchronous style. The return value of a function will provide the result of the asynchronous call. Code written sequentially is typically easier to read, and can even use language features such as exceptions.

So we are going to use coroutines everywhere in this app where we need to wait until a result is available from a long-running task and than continue execution. Lets see one exact implementation for our ViewModel where we will retry getting latest data from the server for our owned cryptocurrencies presented on the main screen.

First add coroutines to the project:

// Coroutines support libraries for Kotlin.

// Dependencies for coroutines.
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$versions.coroutines"

// Dependency is for the special UI context that can be passed to coroutine builders that use
// the main thread dispatcher to dispatch events on the main thread.
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$versions.coroutines"

Than we will create abstract class which will become base class to be used for any ViewModel that needs to have common functionality like coroutines in our case:

abstract class BaseViewModel : ViewModel() {

    // In Kotlin, all coroutines run inside a CoroutineScope.
    // A scope controls the lifetime of coroutines through its job.
    private val viewModelJob = Job()
    // Since uiScope has a default dispatcher of Dispatchers.Main, this coroutine will be launched
    // in the main thread.
    val uiScope = CoroutineScope(Dispatchers.Main + viewModelJob)

    // onCleared is called when the ViewModel is no longer used and will be destroyed.
    // This typically happens when the user navigates away from the Activity or Fragment that was
    // using the ViewModel.
    override fun onCleared() {
        // When you cancel the job of a scope, it cancels all coroutines started in that scope.
        // It's important to cancel any coroutines that are no longer required to avoid unnecessary
        // work and memory leaks.

Here we create specific coroutine scope, which will control the lifetime of coroutines through its job. As you see scope allow you to specify a default dispatcher that controls which thread runs a coroutine. When the ViewModel is no longer used, we cancel viewModelJob and with that every coroutine started by uiScope will be cancelled as well.

Finally implement retry functionality:

 * The ViewModel class is designed to store and manage UI-related data in a lifecycle conscious way.
 * The ViewModel class allows data to survive configuration changes such as screen rotations.

// ViewModel will require a CryptocurrencyRepository so we add @Inject code into ViewModel constructor.
class MainViewModel @Inject constructor(val context: Context, val cryptocurrencyRepository: CryptocurrencyRepository) : BaseViewModel() {


    val mediatorLiveDataMyCryptocurrencyResourceList = MediatorLiveData<Resource<List<MyCryptocurrency>>>()
    private var liveDataMyCryptocurrencyResourceList: LiveData<Resource<List<MyCryptocurrency>>>
    private val liveDataMyCryptocurrencyList: LiveData<List<MyCryptocurrency>>


    // This is additional helper variable to deal correctly with currency spinner and preference.
    // It is kept inside viewmodel not to be lost because of fragment/activity recreation.
    var newSelectedFiatCurrencyCode: String? = null

    // Helper variable to store state of swipe refresh layout.
    var isSwipeRefreshing: Boolean = false

    init {

        // Set a resource value for a list of cryptocurrencies that user owns.
        liveDataMyCryptocurrencyResourceList = cryptocurrencyRepository.getMyCryptocurrencyLiveDataResourceList(cryptocurrencyRepository.getCurrentFiatCurrencyCode())

        // Declare additional variable to be able to reload data on demand.
        mediatorLiveDataMyCryptocurrencyResourceList.addSource(liveDataMyCryptocurrencyResourceList) {
            mediatorLiveDataMyCryptocurrencyResourceList.value = it



     * On retry we need to run sequential code. First we need to get owned crypto coins ids from
     * local database, wait for response and only after it use these ids to make a call with
     * retrofit to get updated owned crypto values. This can be done using Kotlin Coroutines.
    fun retry(newFiatCurrencyCode: String? = null) {

        // Here we store new selected currency as additional variable or reset it.
        // Later if call to server is unsuccessful we will reuse it for retry functionality.
        newSelectedFiatCurrencyCode = newFiatCurrencyCode

        // Launch a coroutine in uiScope.
        uiScope.launch {
            // Make a call to the server after some delay for better user experience.
            updateMyCryptocurrencyList(newFiatCurrencyCode, SERVER_CALL_DELAY_MILLISECONDS)

    // Refresh the data from local database.
    fun refreshMyCryptocurrencyResourceList() {

    // To implement a manual refresh without modifying your existing LiveData logic.
    private fun refreshMyCryptocurrencyResourceList(liveData: LiveData<Resource<List<MyCryptocurrency>>>) {
        liveDataMyCryptocurrencyResourceList = liveData
        { mediatorLiveDataMyCryptocurrencyResourceList.value = it }

    private suspend fun updateMyCryptocurrencyList(newFiatCurrencyCode: String? = null, callDelay: Long = 0) {

        val fiatCurrencyCode: String = newFiatCurrencyCode
                ?: cryptocurrencyRepository.getCurrentFiatCurrencyCode()

        isSwipeRefreshing = true

        // The function withContext is a suspend function. The withContext immediately shifts
        // execution of the block into different thread inside the block, and back when it
        // completes. IO dispatcher is suitable for execution the network requests in IO thread.
        val myCryptocurrencyIds = withContext(Dispatchers.IO) {
            // Suspend until getMyCryptocurrencyIds() returns a result.

        // Here we come back to main worker thread. As soon as myCryptocurrencyIds has a result
        // and main looper is available, coroutine resumes on main thread, and
        // [getMyCryptocurrencyLiveDataResourceList] is called.
        // We wait for background operations to complete, without blocking the original thread.
                (fiatCurrencyCode, true, myCryptocurrencyIds, callDelay))


Here we call a function marked with special Kotlin keyword suspend for coroutines. This means that function suspends execution until the result is ready, then it resumes where it left off with the result. While it is suspended waiting for a result, it unblocks the thread that it is running on. Also in one suspend function we can call another suspend function. As you see we do that by calling new suspend function marked withContext that is executed on different thread. The idea of all this code is that we can combine multiple calls to nice looking sequential code. First we request to get owned cryptocurrencies ids from local database and wait for the response. Only after we get it, we use response ids to make a new call with Retrofit to get updated owned cryptocurrencies values. That is our retry functionality.

We made it! Final thoughts, repository, app & presentation

Congratulations, I am happy if you managed to reach to the end. All the most significant points for creating this app are covered. There was plenty of new stuff done in this part and a lot of that is not covered by this article, but I commented my code everywhere very well, so you should not get lost in it. Check out final code for this part 5 here on GitHub:

The biggest challenge for me personally was not to learn new technologies, not to develop the app, but to write all these articles. Actually I am very happy of myself that I made this challenge. Learning and developing is easy compared to teaching others, but that is where you can understand the topic even better. My advise if you are looking the best way to learn new things start by creating something yourself immediately. I promise you will learn a lot and quickly.

All these articles are based on version 1.0.0 of “Kriptofolio” (previously “My Crypto Coins”) app which you can download as separate APK file here. But I will be very happy if you will install and rate latest app version from the store directly:
Get it on Google Play

Also please feel free to visit simple presentation website that I made for this project:

This post was also republished on Medium. Show your support by clicking the clap button 👏 on the story page here. 😇🙏

1 Comment

Join the discussion and tell us your opinion.

July 16, 2019 at 14:15

Hi Andrius.
Can you please help me initializing the appExecutor class in kotlin? I am not using dependency injection in my app.

Leave a reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.