Use livedata with retrofit android

Updated 28 January 2022

Save

In today’s article we are going to learn how we can use livedata with retrofit. Retrofit allows us to make HTTP calls but it returns Call object. If you are not familiar with retrofit please head over here and here.

Java:

@GET
Call<Model> getData();

Kotlin:

@GET
fun getData() : Call<Model>

But the good thing is retrofit allows us to add custom Call Adapters and Converter factories if we want to get data other than Call objects.

Converter Factory: The converter factory automatically converts the HTTP JSON response into the model (POJO classes) which is why while using retrofit you’ll have to use atleast one converter factory.

The most common is GsonConverterFactory.

Important Note

When using custom converter factories it is important to add a Gson converter factory as the last converter.

Why it is important?

Suppose at any point or for any particular API you do not need to get a response as livedata, in that case, it will look for other converters and if there isn’t any other converter your app will crash.

Let’s Start

We are going to use a third-party library livedata-call-adapter for this article.

  1. Add Dependencies in our app level gradle file (app/gradle). Add following lines.

For demo purposes, we are going to use reqres.in fake rest API that allows us to do fake API calls.

We will get the following responses

Users list

user_list_response

Single User

single_user_response

2. Create retrofit client

3. Create Interface

API Class

4. Create Models

UserResponse Model

User Model

5. Create APiClient

How to use:

  1. Use Live Data Response

Complete MainActivity Code

Custom Call Adapter and Converter

In the above part, we have used a third-party library for livedata call adapter and live data response converter, but what if we want to use our own classes.

Here, we will create our own call adapter and response converter and will see how we can use them as well.

  1. Custom API Response Object (Just like Resource Object in case of library)

2. Live Data Call Adapter

3. Live Data Call Adapter Factory

How to use:

Retrofit Client

ApiInterface

Handle Response

Summary

In this article, we learned how we can use livedata with retrofit to make HTTP calls.

I hope this blog will help you in getting some basic knowledge about retrofit and how to make HTTP calls with retrofit and how you can add custom call adapter and converters.

Thanks for reading!!

author
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Start a Project


    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home