fuel-coroutines
The coroutines extension package for Fuel.
Installation
You can download and install fuel-coroutines with Maven and Gradle. The coroutines package has the following dependencies:
Fuel- KotlinX Coroutines: 1.1.1
1. implementation 'com.github.kittinunf.fuel:fuel:<latest-version>'
2. implementation 'com.github.kittinunf.fuel:fuel-coroutines:<latest-version>'
Usage
Coroutines module provides extension functions to wrap a response inside a coroutine and handle its result. The coroutines-based API provides equivalent methods to the standard API (e.g: responseString() in coroutines is awaitStringResponseResult()).
1. runBlocking {
2. val (request, response, result) = Fuel.get("https://httpbin.org/ip").awaitStringResponseResult()
4. result.fold(
5. { data -> println(data) /* "{"origin":"127.0.0.1"}" */ },
6. { error -> println("An error of type ${error.exception} happened: ${error.message}") }
7. )
8. }
There are functions to handle Result object directly too.
1. runBlocking {
2. Fuel.get("https://httpbin.org/ip")
3. .awaitStringResponseResult()
4. .fold(
5. { data -> println(data) /* "{"origin":"127.0.0.1"}" */ },
6. { error -> println("An error of type ${error.exception} happened: ${error.message}") }
7. )
8. }
It also provides useful methods to retrieve the ByteArray,String or Object directly. The difference with these implementations is that they throw exception instead of returning it wrapped a FuelError instance.
1. runBlocking {
2. try {
3. println(Fuel.get("https://httpbin.org/ip").awaitString()) // "{"origin":"127.0.0.1"}"
4. } catch(exception: Exception) {
5. println("A network request exception was thrown: ${exception.message}")
6. }
7. }
Handling objects other than String (awaitStringResponseResult() ) or ByteArray (awaitByteArrayResponseResult()) can be done using awaitObject, awaitObjectResult or awaitObjectResponseResult.
1. data class Ip(val origin: String)
3. object IpDeserializer : ResponseDeserializable<Ip> {
4. override fun deserialize(content: String) =
5. jacksonObjectMapper().readValue<Ip>(content)
6. }
1. runBlocking {
2. Fuel.get("https://httpbin.org/ip")
3. .awaitObjectResult(IpDeserializer)
4. .fold(
5. { data -> println(data.origin) /* 127.0.0.1 */ },
6. { error -> println("An error of type ${error.exception} happened: ${error.message}") }
7. )
8. }
1. runBlocking {
2. try {
3. val data = Fuel.get("https://httpbin.org/ip").awaitObject(IpDeserializer)
4. println(data.origin) // 127.0.0.1
5. } catch (exception: Exception) {
6. when (exception){
7. is HttpException -> println("A network request exception was thrown: ${exception.message}")
8. is JsonMappingException -> println("A serialization/deserialization exception was thrown: ${exception.message}")
9. else -> println("An exception [${exception.javaClass.simpleName}\"] was thrown")
10. }
11. }
12. }
