Skip to content

Commit fb24fe6

Browse files
authored
Merge pull request #18 from haroldadmin/docs
feat: Add UnknownError docs and fix other misc errors in README
2 parents 58b6a3f + fc57881 commit fb24fe6

File tree

1 file changed

+113
-101
lines changed

1 file changed

+113
-101
lines changed

README.md

Lines changed: 113 additions & 101 deletions
Original file line numberDiff line numberDiff line change
@@ -1,138 +1,146 @@
1-
### NetworkResponse Retrofit adapter
1+
# NetworkResponse Retrofit adapter
22

33
[![Build Status](https://github.com/haroldadmin/networkresponseadapter/workflows/CI/badge.svg)](https://github.com/haroldadmin/networkresponseadapter/actions)
44

55
A call adapter that handles errors as a part of state
66

77
---
8+
89
This library provides a Retrofit call adapter for wrapping your API responses in a `NetworkResponse` class using Coroutines.
910

10-
*This library uses OkHttp 4, which requires Android API version 21+ and Java 8+*
11+
## Network Response
1112

12-
#### Network Response
13-
Network response is a Kotlin sealed class with the following three states:
13+
`NetworkResponse<S, E>` is a Kotlin sealed class with the following states:
1414

15-
1. Success: Used to represent successful responses (2xx response codes, non empty response bodies)
16-
1. ServerError: Used to represent Server errors
17-
1. NetworkError: Used to represent connectivity errors
15+
1. Success: Represents successful responses (2xx response codes)
16+
2. ServerError: Represents Server errors
17+
3. NetworkError: Represents connectivity errors
18+
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)
1819

19-
The sealed class is generic on two types: The response type, and an error type. The response type is your Java/Kotlin representation of the API response, while the error type represents the error response sent by the API server.
20-
The response type represents the Java/Kotlin representation of your API network response. The error type represents your API's error response.
20+
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.
2121

22+
## Usage
2223

23-
#### Usage
24+
- Suppose you have an API that returns the following response if the request is successful:
2425

25-
Suppose you have an API that returns the following response if the request is successful:
26+
_Successful Response_
2627

27-
*Successful Response*
28-
```json
29-
{
28+
```json
29+
{
3030
"name": "John doe",
3131
"age": 21
32-
}
33-
```
34-
35-
And here's the response when the request was unsuccessful:
36-
37-
*Error Response*
38-
```json
39-
{
40-
"message": "The requested person was not found"
41-
}
42-
```
32+
}
33+
```
4334

44-
You can create two data classes to model the these responses:
35+
- And here's the response when the request was unsuccessful:
4536

46-
```kotlin
47-
data class PersonResponse(val name: String, val age: Int)
48-
data class ErrorResponse(val message: String)
49-
```
37+
_Error Response_
5038

51-
You may then write your API service as:
39+
```json
40+
{
41+
"message": "The requested person was not found"
42+
}
43+
```
44+
45+
- You can create two data classes to model the these responses:
46+
47+
```kotlin
48+
data class PersonResponse(val name: String, val age: Int)
49+
data class ErrorResponse(val message: String)
50+
```
51+
52+
- You may then write your API service as:
53+
54+
```kotlin
55+
// APIService.kt
56+
57+
@GET("/person")
58+
fun getPerson(): Deferred<NetworkResponse<PersonResponse, ErrorResponse>>
59+
60+
// or if you want to use Suspending functions
61+
@GET("/person")
62+
suspend fun getPerson(): NetworkResponse<PersonResponse, ErrorResponse>>
63+
```
64+
65+
- Make sure to add this call adapter factory when building your Retrofit instance:
66+
67+
```kotlin
68+
Retrofit.Builder()
69+
.addCallAdapterFactory(NetworkResponseAdapterFactory())
70+
.build()
71+
```
72+
73+
- Then consume the API:
74+
75+
```kotlin
76+
// Repository.kt
77+
78+
suspend fun getPerson() {
79+
val person = apiService.getPerson().await()
80+
// or if you use suspending functions,
81+
val person = apiService.getPerson()
82+
83+
when (person) {
84+
is NetworkResponse.Success -> {
85+
// Handle successful response
86+
}
87+
is NetworkResponse.ServerError -> {
88+
// Handle server error
89+
}
90+
is NetworkResponse.NetworkError -> {
91+
// Handle network error
92+
}
93+
is NetworkResponse.UnknownError -> {
94+
// Handle other errors
95+
}
96+
}
97+
}
98+
```
5299

100+
- You can also use the included utility function `executeWithRetry` to automatically retry your network requests if they result in `NetworkResponse.NetworkError`
53101

54-
```kotlin
55-
// APIService.kt
102+
```kotlin
103+
suspend fun getPerson() {
104+
val response = executeWithRetry(times = 5) {
105+
apiService.getPerson.await()
106+
}
56107

57-
@GET("<api-url>")
58-
fun getPerson(): Deferred<NetworkResponse<PersonResponse, ErrorResponse>>
108+
// or with suspending functions
109+
val response = executeWithRetry(times = 5) {
110+
apiService.getPerson()
111+
}
59112

60-
// or if you want to use Suspending functions
61-
@GET("<api-url>")
62-
suspend fun getPerson(): NetworkResponse<PersonResponse, ErrorResponse>>
63-
```
113+
// Then handle the response
114+
}
115+
```
64116

65-
Make sure to add this call adapter factory when building your Retrofit instance:
66-
```kotlin
67-
Retrofit.Builder()
68-
.addCallAdapterFactory(NetworkResponseAdapterFactory())
69-
.build()
70-
```
117+
- There's also an overloaded invoke operator on the NetworkResponse class which returns the success body if the request was successful, or null otherwise
71118

72-
Then consume the API as follows:
73-
74-
```kotlin
75-
// Repository.kt
76-
77-
suspend fun getPerson() {
78-
val person = apiService.getPerson().await()
79-
// or if you use suspending functions,
80-
val person = runBlocking { apiService.getPerson() }
81-
82-
when (person) {
83-
is NetworkResponse.Success -> {
84-
// Handle Success
85-
}
86-
is NetworkResponse.ServerError -> {
87-
// Handle Server Error
88-
}
89-
is NetworkResponse.NetworkError -> {
90-
// Handle Network Error
91-
}
92-
}
93-
}
94-
```
119+
```kotlin
120+
val usersResponse = usersRepo.getUsers().await()
121+
println(usersResponse() ?: "No users were found")
122+
```
95123

96-
You can also use the included utility function `executeWithRetry` to automatically retry your network requests if they result in `NetworkResponse.NetworkError`
97-
```kotlin
98-
suspend fun getPerson() {
99-
val response = executeWithRetry(times = 5) {
100-
apiService.getPerson.await()
101-
}
102-
103-
// or with suspending functions
104-
val response = executeWithRetry(times = 5) {
105-
apiService.getPerson()
106-
}
107-
108-
// Then handle the response
109-
}
110-
```
124+
- Some API responses convey information through headers only, and contain empty bodies. Such endpoints must be used with `Unit` as their success type.
111125

112-
There's also an overloaded invoke operator on the NetworkResponse class so that its success body can be accessed directly.
113-
```kotlin
114-
val usersResponse = usersRepo.getUsers().await()
115-
println(usersResponse() ?: "No users were found") // Returns users if response is successful, or null otherwise
116-
```
126+
```kotlin
127+
@GET("/empty-body-endpoint")
128+
suspend fun getEmptyBodyResponse(): NetworkResponse<Unit, ErrorType>
129+
```
117130

118131
---
119132

120-
#### Why?
121-
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. Server errors and Connectivity problems can be easily dealt with.
122-
For any other unexpected situation, you probably want to crash your application so that you can take a look at what's going on.
133+
## Benefits
123134

124-
The `NetworkResponse` adapter provides a much cleaner solution than Retrofit's built in `Call` type, because it models errors as a sealed class and does not force you to think in terms of callbacks.
125-
It is built on top of coroutines support, so asynchronous network requests become a lot easier too!
135+
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!
126136

127-
The RxJava retrofit adapter treats non 2xx error codes as errors too, which seems silly. An error in an Rx stream should be something from which it is difficult to recover.
128-
This is not the best way to deal with errors from an API response, because they can contain meaningful information too. They should not be specifically dealt with in `onError` blocks.
137+
- `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.
129138

130-
However, because a lot of things are treated as errors in the Rx Adapter, retrying becomes as easy as dropping the `retry()` operator in the middle of the stream.
139+
- 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.
131140

132-
While the solution provided by this library is not as convenient as that, you can take a look at the `executeWithRetry` utility method.
133-
It is a higher order function which can retry your network requests if they fail.
141+
- Using the `Response` class provided by Retrofit is cumbersome, as you have to manually parse error bodies with it.
134142

135-
#### Installation
143+
## Installation
136144

137145
Add the Jitpack repository to your list of repositories:
138146

@@ -145,16 +153,20 @@ allprojects {
145153
```
146154

147155
And then add the dependency in your gradle file:
156+
148157
```groovy
149158
dependencies {
150159
implementation "com.github.haroldadmin:NetworkResponseAdapter:(latest-version)"
151160
}
152161
```
153162

163+
_This library uses OkHttp 4, which requires Android API version 21+ and Java 8+_
164+
154165
[![Release](https://jitpack.io/v/haroldadmin/NetworkResponseAdapter.svg)](https://jitpack.io/#haroldadmin/NetworkResponseAdapter)
155166

156-
#### License
157-
```
167+
## License
168+
169+
```text
158170
Licensed under the Apache License, Version 2.0 (the "License");
159171
you may not use this file except in compliance with the License.
160172
You may obtain a copy of the License at

0 commit comments

Comments
 (0)