All Projects → haroldadmin → Networkresponseadapter

haroldadmin / Networkresponseadapter

Licence: apache-2.0
A Kotlin Coroutines based Retrofit call adapter that handles errors as a part of state

Programming Languages

kotlin
9241 projects

Projects that are alternatives of or similar to Networkresponseadapter

WanAndroidJetpack
🔥 WanAndroid 客户端,Kotlin + MVVM + Jetpack + Retrofit + Glide。基于 MVVM 架构,用 Jetpack 实现,网络采用 Kotlin 的协程和 Retrofit 配合使用!精美的 UI,便捷突出的功能实现,欢迎下载体验!
Stars: ✭ 124 (-49.59%)
Mutual labels:  retrofit, kotlin-coroutines
GitMessengerBot-Android
타입스크립트, V8 엔진의 자바스크립트, 파이썬 그리고 Git을 지원하는 최첨단 메신저 봇!
Stars: ✭ 51 (-79.27%)
Mutual labels:  retrofit, kotlin-coroutines
Photos
No description or website provided.
Stars: ✭ 74 (-69.92%)
Mutual labels:  retrofit, kotlin-coroutines
Kotlin Coroutines Retrofit
Kotlin Coroutines await() extension for Retrofit Call
Stars: ✭ 812 (+230.08%)
Mutual labels:  kotlin-coroutines, retrofit
Eiffel
Redux-inspired Android architecture library leveraging Architecture Components and Kotlin Coroutines
Stars: ✭ 203 (-17.48%)
Mutual labels:  kotlin-coroutines
Android Kotlin Mvi Cleanarchitecture
Android + Kotlin + Modularization + Gradle Depedency managment + Gradle written in Kotlin DSL + Custom Gradle Plugin + MVVM + MVI + Clean Architecture + Repository Pattern + Coroutines + Flows + Koin + Retrofit2 + ROOM + Kotlin-Android-Extension + KtLints
Stars: ✭ 187 (-23.98%)
Mutual labels:  retrofit
Androidbasemvp
🚀一个快速搭建MVP+RxJava2+Retrofit 基础框架,主要是封装有Http网络请求、日志、缓存、加载等待、toast、页面状态布局管理、权限、RxBus、Glide图片加载等组件,方便快速开发新项目、减少开发成本。
Stars: ✭ 184 (-25.2%)
Mutual labels:  retrofit
Android Clean Arch Coroutines Koin
Implemented by Clean Architecture, MVVM, Koin, Coroutines, Moshi, Mockk, LiveData & DataBinding
Stars: ✭ 173 (-29.67%)
Mutual labels:  kotlin-coroutines
Newandroidarchitecture Component Github
Sample project based on the new Android Component Architecture
Stars: ✭ 229 (-6.91%)
Mutual labels:  retrofit
Progressmanager
⏳ Listen the progress of downloading and uploading in Okhttp, compatible Retrofit and Glide (一行代码即可监听 App 中所有网络链接的上传以及下载进度, 包括 Glide 的图片加载进度).
Stars: ✭ 2,463 (+901.22%)
Mutual labels:  retrofit
Wanandroid
玩安卓java客户端http://www.wanandroid.com/ 模块化客户端,运用MVP+Retrofit+Rxjava+Rxlifecycle+Glide+Eventbus+ARouter等架构,构建一个最简洁的玩安卓app。
Stars: ✭ 199 (-19.11%)
Mutual labels:  retrofit
Retrofitutils
retrofit网络工具类
Stars: ✭ 188 (-23.58%)
Mutual labels:  retrofit
Kord
Idiomatic Kotlin Wrapper for The Discord API
Stars: ✭ 203 (-17.48%)
Mutual labels:  kotlin-coroutines
Cookman
一款菜谱查询工具Android APP
Stars: ✭ 186 (-24.39%)
Mutual labels:  retrofit
Firebase Kotlin Sdk
A Kotlin-first SDK for Firebase
Stars: ✭ 214 (-13.01%)
Mutual labels:  kotlin-coroutines
Droid Feed
Aggregated Android news, articles, podcasts and conferences about Android Development
Stars: ✭ 174 (-29.27%)
Mutual labels:  kotlin-coroutines
Kable
Kotlin Asynchronous Bluetooth Low-Energy
Stars: ✭ 194 (-21.14%)
Mutual labels:  kotlin-coroutines
Bikeshare
Jetpack Compose and SwiftUI based Kotlin Multiplatform project (using CityBikes API http://api.citybik.es/v2/).
Stars: ✭ 206 (-16.26%)
Mutual labels:  kotlin-coroutines
Vector
Kotlin Coroutines based MVI architecture library for Android
Stars: ✭ 194 (-21.14%)
Mutual labels:  kotlin-coroutines
Component
🔥🔥🔥A powerful componentized framework.一个强大、100% 兼容、支持 AndroidX、支持 Kotlin并且灵活的组件化框架
Stars: ✭ 2,434 (+889.43%)
Mutual labels:  retrofit

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 Retrofit call adapter for wrapping your API responses in a NetworkResponse class using Coroutines.

Network Response

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

  1. Success: Represents successful responses (2xx response codes)
  2. ServerError: Represents Server errors
  3. NetworkError: Represents connectivity errors
  4. UnknownError: Represents every other kind of error which can not be classified as an API error or a network problem (eg JSON deserialization exceptions)

It is generic on two types: a response (S), and an error (E). The response type is your Java/Kotlin representation of the API response, while the error type represents the error response sent by the API.

Usage

  • Suppose you have an API that returns the following response if the request is successful:

    Successful Response

    {
      "name": "John doe",
      "age": 21
    }
    
  • And here's the response when the request was unsuccessful:

    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)
    
  • You may then write your API service as:

    // APIService.kt
    
    @GET("/person")
    fun getPerson(): Deferred<NetworkResponse<PersonResponse, ErrorResponse>>
    
    // or if you want to use Suspending functions
    @GET("/person")
    suspend fun getPerson(): NetworkResponse<PersonResponse, ErrorResponse>>
    
  • Make sure to add this call adapter factory when building your Retrofit instance:

    Retrofit.Builder()
        .addCallAdapterFactory(NetworkResponseAdapterFactory())
        .build()
    
  • Then consume the API:

    // Repository.kt
    
    suspend fun getPerson() {
        val person = apiService.getPerson().await()
        // or if you use suspending functions,
        val person = apiService.getPerson()
    
        when (person) {
            is NetworkResponse.Success -> {
                // Handle successful response
            }
            is NetworkResponse.ServerError -> {
                // Handle server error
            }
            is NetworkResponse.NetworkError -> {
                // Handle network error
            }
            is NetworkResponse.UnknownError -> {
                // Handle other errors
            }
        }
    }
    
  • You can also use the included utility function executeWithRetry to automatically retry your network requests if they result in NetworkResponse.NetworkError

    suspend fun getPerson() {
        val response = executeWithRetry(times = 5) {
            apiService.getPerson.await()
        }
    
        // or with suspending functions
        val response = executeWithRetry(times = 5) {
            apiService.getPerson()
        }
    
        // Then handle the response
    }
    
  • There's also an overloaded invoke operator on the NetworkResponse class which returns the success body if the request was successful, or null otherwise

    val usersResponse = usersRepo.getUsers().await()
    println(usersResponse() ?: "No users were found")
    
  • Some API responses convey information through headers only, and contain empty bodies. Such endpoints must be used with Unit as their success type.

    @GET("/empty-body-endpoint")
    suspend fun getEmptyBodyResponse(): NetworkResponse<Unit, ErrorType>
    

Benefits

Modelling errors as a part of your state is a recommended practice. 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 an 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 subtype.

  • 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.
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].