Using Retrofit with LiveData

Pi Vincii
Pi Vincii
Jan 12 · 2 min read

I. Livedata

In 2017, Android Architecture Components was released by Google, helps Android Developer build robust, maintain, stable app. Livedata is a part in the collections of libraries introduced in Android Architecture Components.

According to Android Document:
LiveData is an observable data holder class. Unlike a regular observable, LiveData is lifecycle-aware, meaning it respects the lifecycle of other app components, such as activities, fragments, or services. This awareness ensures LiveData only updates app component observers that are in an active lifecycle state.

If you have worked with RxJava/RxKotlin before, you will find it easy to understand LiveData.

One typical case to use Livedata is holding view data. View will listen to Livedata object, and data change will update via Livedata.

Example from Android Document Page: (

II. Use retrofit with LiveData

As the title of this article, we are not going to describe Livedata. What we want is: retrofit return Livedata object when requesting restful API.

Here is what we want: (

By default, Retrofit will return Call data holder object. Fortunately, retrofit is smart, it provides us `addCallAdapterFactory()` which helps us return whatever we want, not only `Call`. What we need to do to achieve our goal is to create a CallAdapter.Factory. It will help us convert Call to Object which we want.

Firstly, we need a LiveDataCallAdapter which turns Call to Livedata. (

We will notice about `ApiResponse` object, why we need to have that. Well, unfortunately, Livedata doesn’t provide any error callback or observer like rxJava. So we need to wrap data return by ApiResponse to handle the error cases.

Here is how ApiResponse look like (

Now, we can create a Factory for that adapter. (

And finally, setting retrofit. (

Ok, finally, now is the time to use (

However, the way we are using here is like a one-shot use, and look like Retrofit won’t support Livedata. Read more here:

We still have some problem with the above methods:
1. How can we refresh data?
2. Wrap response looks not dry?

Do you have any solution for that?

If my article helps you, or if it brings to you something, Please give me one clap :) It will bring happiness to me to contribute/sharing my work. Thank you!!!

Full source code:

Pi Vincii

Written by

Pi Vincii

Writing for remembering

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade