Android App Development
iOS App Development
Flutter App Development
Cross Platform App Development
Hire on-demand project developers and turn your idea into working reality.
Big thanks to Webkul and his team for helping get Opencart 126.96.36.199 release ready!
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.
@GETfun 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.
When using custom converter factories it is important to add a Gson converter factory as the last converter.
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.
We are going to use a third-party library livedata-call-adapter for this article.
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
2. Create retrofit client
3. Create Interface
4. Create Models
5. Create APiClient
How to use:
Complete MainActivity Code
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.
2. Live Data Call Adapter
3. Live Data Call Adapter Factory
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!!
Your email address will not be published. Required fields are marked*
Save my name email and website in this browser for the next time I comment.
Be the first to comment.
It was a successful collaboration. The Mobikul team provided the client everything they needed in a timely and high-quality manner. They were very professional, reliable, and accessible during the entire process. The client also saw no room for any improvements in the vendor's performance.
Enquiry or Requirement
If you have more details or questions, you can reply to the received confirmation email.