Giter Site home page Giter Site logo

ritesh-singh / networkresponseadapter Goto Github PK

View Code? Open in Web Editor NEW

This project forked from haroldadmin/networkresponseadapter

0.0 0.0 0.0 1.35 MB

A Coroutines based Retrofit call adapter that lets you model successful and failed responses easily

Home Page: https://haroldadmin.github.io/NetworkResponseAdapter

License: Apache License 2.0

Kotlin 100.00%

networkresponseadapter's Introduction

NetworkResponse Retrofit adapter

Build Status

https://haroldadmin.github.io/NetworkResponseAdapter/

A call adapter that handles errors as a part of state


This library provides a Kotlin Coroutines based Retrofit call adapter for wrapping your API responses in a NetworkResponse type.

Network Response

NetworkResponse<S, E> is a Kotlin sealed interface with the following states:

  • Success: Represents successful network calls (2xx response codes)
  • Error: Represents unsuccessful network calls
    • ServerError: Server errors (non 2xx responses)
    • NetworkError: IO Errors, connectivity problems
    • UnknownError: Any other errors, like serialization exceptions

It is generic on two types: a success response (S), and an error response (E).

  • S: Kotlin representation of a successful API response
  • E: Representation of an unsuccessful API response

Usage

Suppose an API returns the following body for a successful response:

Successful Response

{
  "name": "John doe",
  "age": 21
}

And this for an unsuccessful response:

Error Response

{
  "message": "The requested person was not found"
}

You can create two data classes to model the these responses:

data class PersonResponse(val name: String, val age: Int)

data class ErrorResponse(val message: String)

Then modify your Retrofit service to return a NetworkResponse:

@GET("/person")
suspend fun getPerson(): NetworkResponse<PersonResponse, ErrorResponse>>

// You can also request for `Deferred` responses
@GET("/person")
fun getPersonAsync(): Deferred<NetworkResponse<PersonResponse, ErrorResponse>>

Finally, add this call adapter factory to your Retrofit instance:

Retrofit.Builder()
    .addCallAdapterFactory(NetworkResponseAdapterFactory())
    .build()

And voila! You can now consume your API as:

// Repository.kt
suspend fun getPerson() {
    when (val person = apiService.getPerson()) {
        is NetworkResponse.Success -> {
            /* Successful response */
        }
        is NetworkResponse.Error -> {
            /* Handle error */
        }
    }

    // Or, if you care about the type of the error:
    when (val person = apiService.getPerson()) {
        is NetworkResponse.Success -> {
            /* ... */
        }
        is NetworkResponse.ServerError -> {
            /* ... */
        }
        is NetworkResponse.NetworkError -> {
            /* ... */
        }
        is NetworkResponse.UnknownError -> {
            /* ... */
        }
    }
}

Utilities

Retry Failed Network Calls

Use the included utility function executeWithRetry to automatically retry your network requests if they result in a NetworkResponse.NetworkError

suspend fun getPerson() {
    val response = executeWithRetry(times = 5) {
        apiService.getPerson()
    }
}

Overloaded invoke() on NetworkResponse

The NetworkResponse interface has an overloaded invoke() operator that returns the success body if the request was successful, or null otherwise

val usersResponse = usersRepo.getUsers()
println(usersResponse() ?: "No users were found")

Handle Empty Response Bodies

Some API responses convey information through headers only and contain empty bodies. Use Unit to represent the success response type of such network calls.

@DELETE("/person")
suspend fun deletePerson(): NetworkResponse<Unit, ErrorType>

Benefits

This library helps you deal with scenarios where you can successfully recover from errors, and extract meaningful information from them too!

  • NetworkResponseAdapter provides a much cleaner solution than Retrofit's built in Call type for dealing with errors.Call throws an exception on any kind of error, leaving it up to you to catch it and parse it manually to figure out what went wrong. NetworkResponseAdapter does all of that for you and returns the result in an easily consumable NetworkResponse type.

  • The RxJava retrofit adapter treats non 2xx response codes as errors, which seems silly in the context of Rx where errors terminate streams. Also, just like the Call<T> type, it makes you deal with all types of errors in an onError callback, where you have to manually parse it to find out exactly what went wrong.

  • Using the Response class provided by Retrofit is cumbersome, as you have to manually parse error bodies with it.

Installation

Add the Jitpack repository to your list of repositories:

allprojects {
    repositories {
        maven { url 'https://jitpack.io' }
    }
}

And then add the dependency in your gradle file:

dependencies {
    implementation "com.github.haroldadmin:NetworkResponseAdapter:(latest-version)"
}

This library uses OkHttp 4, which requires Android API version 21+ and Java 8+

Release

License

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

networkresponseadapter's People

Contributors

haroldadmin avatar garrytrue avatar dependabot[bot] avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.