Android

Customization of RestApi call using Retrofit and RxJava in Kotlin

Assuming you all are well aware of Retrofit and RxJava. Today I am going to write about how you can customize your RestApi call using Retrofit and RxJava. This will make your project neat and clean. We will build a class from where all our GET and POST request will be handled.

Features:

  • Check your internet is on or off in one place.
  • If internet is off, then it will pop up a retry dialog, will help users to reconnect.
  • Error is handled in one place.

Benefits:

  • Make your code readable, maintainable, and the best part is it is reactive
  • Once your customization is placed, you don’t need to worry about your every call.
  • Your customization, your code, helps you to work fast.

Let’s start,

  1. Create a library called custom. From where you can access it in your whole project. [I won’t show here how to create a library in Android Studio -> Try at your own risk. (Take risk to get benefited)]

Add these below code in your custom library.

These is Retrofit singleton class.

This is the customized callback class from where I can manipulate my RestApi response. Function override for different purposes.

Sometimes I don’t need internet pop up dialog. it can be handled through function. Sometime you need only background update, don’t need to alert users, This time pass false for pop up dialog. That’s it. Easy!! right? Yeah it is easy and cool :

Credit: Touhid vai (Co-founder. Durbin Labs Ltd )

 

MyLogginInterceptor:

To handle api authorization, api log.

Sometimes we need authorization, right? Sending authorization with every call is not developer friendly. So this logging interceptor will help you to pass token or authorization that needs to be in all of your api urls.

 

Some useful interfaces that I used in this project

 

// Purpose of this callback is to get single object or single data. Example: (User (var id: Int, var name: String) model class)

This callback helps you to initialize the api call again. User friendly. Right? Hell! yeah right.

 

The main call happens here which serves my purpose. 🙂 Call this in your Activity.

 

Easy!! Isn’t it?

Share your thoughts. Give ideas. I will try to make it rich. Thanks 🙂

Happy Coding……….

 

Leave a Reply

Your email address will not be published.

two × 5 =