Response Handler (Retrofit + Co-routine)

Ashutosh jha
Dev Genius

--

Pre-requisites : Worked with Retrofit (Android library) and knowledge of Co-routine (Kotlin)

While using retrofit for network calls, it’s been a bit tricky to handle the response, specially when you are trying to handle network exceptions. One discripency and your application might crash. There are two ways to deal with it:

  1. Make multiple network calls and handle each responses one-by-one.
  2. You just need to give your response (whatever it is) and in turn you will get the desired response or the callbacks for various exceptions if any.

Let’s moving to the code…

Step 1: Define your request

Note : The response should be of type Response<T>

Step 2: Call the API and pass the response to handler

Handler

Note: This will return the defined response if the response code is 200 or null otherwise. You can also modify response or add logic for specific response codes as per your need.

Thanks for reading. Any correction will be welcomed.

--

--

Techie from 🇮🇳 | Writing blogs on Android, Flutter, UI/UX and many more. Lead Engineer