NetworkResponse
NetworkResponse is a sealed class to wrap responses from network requests:
Success[data,codeandheaders]Error[error,codeandheaders]UnknownError[throwable]RemoteNotAvailableInternetNotAvailable
This library works very well when used in conjunction with Resource which is very similar to NetworkResponse but thought to use with another architecture layer, for example domain objects. NetworkResponse has mappers to transform it to a Resource.
Features
- Multiplatform (NetworkResponse and Resource support)
- Retrofit support (jvm)
- Ktor support
Download
This library is Kotlin Multiplatform but at this moment jvm is the only artifact generated. It is available at Maven Central.
implementation("com.javiersc.network-response:network-response:$version")
Retrofit
This adapter for Retrofit wraps automatically the Retrofit responses with a NetworkResponse:
@GET("users")
suspend fun getUsers(): NetworkResponse<List<UserDTO>, ErrorDTO>
// UserDTO and ErrorDTO should be your data classes
If the server doesn't return an error body, or it is irrelevant you can mark it as Unit:
@GET("users")
suspend fun getUsers(): NetworkResponse<List<UserDTO>, Unit>
Add the NetworkResponseCallAdapterFactory to the Retrofit builder:
private val retrofit = Retrofit.Builder().apply {
//...
addCallAdapterFactory(NetworkResponseCallAdapterFactory())
//...
}.build()
It is possible to use Deferred too:
@GET("users")
fun getUsers(): Deferred<NetworkResponse<List<UserDTO>, ErrorDTO>>
Ktor
You only need to wrap the request and do not indicate the type in the client method because it is inferred automatically
val usersNetworkResponse = NetworkResponse<List<UsersDTO>, ErrorDTO> { client.get("https://example.com/users") }
More artifacts
Credits
Based on NetworkResponseAdapter by Kshitij Chauhan