Skip to content

Commit 8773c53

Browse files
committed
feat: Add UnknownError docs and fix other misc errors in README
1 parent 58b6a3f commit 8773c53

File tree

1 file changed

+108
-103
lines changed

1 file changed

+108
-103
lines changed

README.md

Lines changed: 108 additions & 103 deletions
Original file line numberDiff line numberDiff line change
@@ -1,138 +1,139 @@
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-
```
43-
44-
You can create two data classes to model the these responses:
45-
46-
```kotlin
47-
data class PersonResponse(val name: String, val age: Int)
48-
data class ErrorResponse(val message: String)
49-
```
32+
}
33+
```
5034

51-
You may then write your API service as:
35+
- And here's the response when the request was unsuccessful:
5236

37+
_Error Response_
5338

54-
```kotlin
55-
// APIService.kt
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+
```
5699

57-
@GET("<api-url>")
58-
fun getPerson(): Deferred<NetworkResponse<PersonResponse, ErrorResponse>>
100+
- You can also use the included utility function `executeWithRetry` to automatically retry your network requests if they result in `NetworkResponse.NetworkError`
59101

60-
// or if you want to use Suspending functions
61-
@GET("<api-url>")
62-
suspend fun getPerson(): NetworkResponse<PersonResponse, ErrorResponse>>
63-
```
102+
```kotlin
103+
suspend fun getPerson() {
104+
val response = executeWithRetry(times = 5) {
105+
apiService.getPerson.await()
106+
}
64107

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-
```
108+
// or with suspending functions
109+
val response = executeWithRetry(times = 5) {
110+
apiService.getPerson()
111+
}
71112

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-
```
113+
// Then handle the response
114+
}
115+
```
95116

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-
```
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
111118

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-
```
119+
```kotlin
120+
val usersResponse = usersRepo.getUsers().await()
121+
println(usersResponse() ?: "No users were found")
122+
```
117123

118124
---
119125

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.
126+
## Benefits
123127

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!
128+
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!
126129

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.
130+
- `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.
129131

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.
132+
- 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.
131133

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.
134+
- Using the `Response` class provided by Retrofit is cumbersome, as you have to manually parse error bodies with it.
134135

135-
#### Installation
136+
## Installation
136137

137138
Add the Jitpack repository to your list of repositories:
138139

@@ -145,16 +146,20 @@ allprojects {
145146
```
146147

147148
And then add the dependency in your gradle file:
149+
148150
```groovy
149151
dependencies {
150152
implementation "com.github.haroldadmin:NetworkResponseAdapter:(latest-version)"
151153
}
152154
```
153155

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

156-
#### License
157-
```
160+
## License
161+
162+
```text
158163
Licensed under the Apache License, Version 2.0 (the "License");
159164
you may not use this file except in compliance with the License.
160165
You may obtain a copy of the License at

0 commit comments

Comments
 (0)