Skip to content

Commit

Permalink
update README.md
Browse files Browse the repository at this point in the history
  • Loading branch information
yujinyan committed May 2, 2021
1 parent 2440303 commit 32eea99
Showing 1 changed file with 28 additions and 4 deletions.
32 changes: 28 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
# Retrofit Kotlin Result Adapter
# Retrofit Suspend Kotlin Result Adapter

[![Release](https://jitpack.io/v/yujinyan/retrofit-suspend-result-adapter.svg?style=flat-square)](https://jitpack.io/#User/Repo)

A Retrofit 2 `CallAdapter.Factory` for Kotlin suspend functions that use the standard
library [`kotlin.Result`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-result/) as return value. The call
adapter catches all exceptions so that there is no need to try catch suspend functions at call sites.
adapter catches network failures / deserialization errors so that there is no need to try catch suspend functions at
call sites.

Many useful methods are available on the `Result` type. Once [Kotlin allows null-safety operators `?.`, `?:` and `!!`
on `Result`](https://github.com/Kotlin/KEEP/pull/244), the ergonomics of using this type will be greatly improved.
Expand Down Expand Up @@ -42,14 +45,35 @@ lifecycleScope.launch {

## Failure handler

You can register a default failure handler through the constructor.
You can register a default failure handler through the constructor. This is a good place for configuring global error
handling logic.

```kotlin
val retrofit = Retrofit.Builder()
.baseUrl("https://")
.baseUrl("https://example.com")
.addCallAdapterFactory(SuspendResultCallAdapterFactory {
report(it)
})
.addConverterFactory(MoshiConverterFactory.create(moshi))
.build()
```

## Custom converter for `Result<T>`

If your API returns data wrapped in an "envelop", it may be a good idea to unwrap the data and place it in `Result`
directly.

Suppose the API response looks like this. You can still use `Result<User>` as return type.

```json
{
"errcode": 0,
"data": {
"id": 1,
"name": "Peter"
}
}
```

To achieve this, write a custom converter.
Checkout [CustomConverterTest](src/test/kotlin/me/yujinyan/retrofit/CustomConverterTest.kt) for an example.

0 comments on commit 32eea99

Please sign in to comment.