Best Fuel code snippet using com.github.kittinunf.fuel.core.Deserializable
FuelWebService.kt
Source:FuelWebService.kt
...3import com.github.kittinunf.fuel.core.FuelError4import com.github.kittinunf.fuel.core.FuelManager5import com.github.kittinunf.fuel.core.Request6import com.github.kittinunf.fuel.core.Response7import com.github.kittinunf.fuel.core.ResponseDeserializable8import com.github.kittinunf.result.Result9import com.google.gson.Gson10import com.google.gson.JsonSyntaxException11import me.shkschneider.skeleton.helper.ApplicationHelper12import me.shkschneider.skeleton.helperx.Logger13import java.util.concurrent.TimeUnit14import kotlin.Result.Companion.success15import kotlin.reflect.KClass16open class FuelWebService(val gson: Gson = Gson()) {17 init {18 if (ApplicationHelper.debuggable()) {19 FuelManager.instance.addRequestInterceptor { next: (Request) -> Request ->20 { request: Request ->21 Logger.info(request.toString())22 next(request)23 }24 }25 FuelManager.instance.addResponseInterceptor { next: (Request, Response) -> Response ->26 { request: Request, response: Response ->27 Logger.info(response.toString())28 next(request, response)29 }30 }31 }32 FuelManager.instance.timeoutInMillisecond = TimeUnit.SECONDS.toMillis(15).toInt()33 FuelManager.instance.timeoutReadInMillisecond = TimeUnit.SECONDS.toMillis(15).toInt()34 }35 inline fun <reified T: Any> get(url: String,36 crossinline success: (Request, Response, T) -> Unit,37 noinline failure: ((Request, Response, Exception) -> Unit)? = null38 ): Request = request<T>(Fuel.get(url), success, failure)39 inline fun <reified T: Any> head(url: String,40 crossinline success: (Request, Response, T) -> Unit,41 noinline failure: ((Request, Response, Exception) -> Unit)? = null42 ): Request = request<T>(Fuel.head(url), success, failure)43 inline fun <reified T: Any> post(url: String,44 crossinline success: (Request, Response, T) -> Unit,45 noinline failure: ((Request, Response, Exception) -> Unit)? = null46 ): Request = request<T>(Fuel.post(url), success, failure)47 inline fun <reified T: Any> put(url: String,48 crossinline success: (Request, Response, T) -> Unit,49 noinline failure: ((Request, Response, Exception) -> Unit)? = null50 ): Request = request<T>(Fuel.put(url), success, failure)51 inline fun <reified T: Any> delete(url: String,52 crossinline success: (Request, Response, T) -> Unit,53 noinline failure: ((Request, Response, Exception) -> Unit)? = null54 ): Request = request<T>(Fuel.delete(url), success, failure)55 @Deprecated("@hide")56 inline fun <reified T: Any> request(request: Request,57 crossinline success: (Request, Response, T) -> Unit,58 noinline failure: ((Request, Response, Exception) -> Unit)? = null59 ): Request = request.responseObject(Deserializer(gson, T::class)) { _, response, result: Result<T, FuelError> ->60 result.fold({ data ->61 success(request, response, data)62 }, { fuelError ->63 Logger.error("${fuelError.response.statusCode} ${fuelError.response.url}", fuelError.exception)64 failure?.invoke(request, response, fuelError.exception)65 })66 }67 inline fun <reified T: Any> deserialize(content: String): T? =68 Deserializer(gson, T::class).deserialize(content)69 inner class Deserializer<T: Any>(private val gson: Gson, private val klass: KClass<T>): ResponseDeserializable<T> {70 override fun deserialize(content: String): T? {71 try {72 return gson.fromJson(content, klass.java)73 } catch (e: JsonSyntaxException) {74 Logger.wtf(e)75 return null76 }77 }78 }79}...
MainViewModel.kt
Source:MainViewModel.kt
...6import com.example.androiddevchallenge.Models.Response.PuppyModel7import com.example.androiddevchallenge.Models.Response.ResponseModel8import com.github.kittinunf.fuel.Fuel9import com.github.kittinunf.fuel.core.HttpException10import com.github.kittinunf.fuel.core.ResponseDeserializable11import com.github.kittinunf.fuel.coroutines.awaitObject12import com.github.kittinunf.fuel.coroutines.awaitObjectResponseResult13import com.github.kittinunf.result.Result14import com.github.kittinunf.fuel.gson.responseObject15import com.google.gson.Gson16import kotlinx.coroutines.runBlocking17class MainViewModel : ViewModel() {18 val puppies : MutableState<List<PuppyModel>> = mutableStateOf(ArrayList())19 val query = mutableStateOf("")20 val loading = mutableStateOf(false)21 fun onQueryChange(value : String){22 query.value = value23 }24 init {25 getPuppies()26 }27 fun getPuppies(){28 val items = mutableListOf<PuppyModel>()29 runBlocking {30 loading.value = true31 try {32 var result = Fuel.get("https://dog.ceo/api/breeds/list/all").awaitObject(DeserializerResponseModel())33 for ((key, value) in result.message) {34 var url = "https://dog.ceo/api/breed/${key}/images/random"35 val data = Fuel.get(url).awaitObject(Deserializer())36 items.add(PuppyModel(breed = key,imageUrl = data.message, subBreed = value))37 }38 puppies.value = items39 loading.value = false40 } catch (exception: Exception) {41 when (exception){42 is HttpException -> println("A network request exception was thrown: ${exception.message}")43 else -> println("An exception [${exception.javaClass.simpleName}\"] was thrown")44 }45 loading.value = false46 }47 }48 }49 class Deserializer : ResponseDeserializable<GetImage> {50 override fun deserialize(reader: java.io.Reader) = Gson().fromJson(reader, GetImage::class.java)!!51 }52 class DeserializerResponseModel : ResponseDeserializable<ResponseModel> {53 override fun deserialize(reader: java.io.Reader) = Gson().fromJson(reader, ResponseModel::class.java)!!54 }55// class ListDeserializer : ResponseDeserializable<List<Issue>> {56// override fun deserialize(reader: Reader): List<Issue> {57// val type = object : TypeToken<List<Issue>>() {}.type58// return Gson().fromJson(reader, type)59// }60// }61}...
UserService.kt
Source:UserService.kt
23import com.github.kittinunf.fuel.Fuel4import com.github.kittinunf.fuel.core.FuelManager5import com.github.kittinunf.fuel.core.Request6import com.github.kittinunf.fuel.core.ResponseDeserializable7import com.github.kittinunf.fuel.coroutines.awaitObjectResult8import com.github.kittinunf.fuel.coroutines.awaitStringResult9import com.google.gson.Gson10import dev.paranoid.data.repository.Chat11import dev.paranoid.data.repository.ID12import dev.paranoid.data.repository.User13import kotlinx.coroutines.Dispatchers14import kotlinx.coroutines.withContext1516suspend inline fun <reified T : Any> Request.to() =17 awaitObjectResult<T>(object : ResponseDeserializable<T> {18 override fun deserialize(content: String) = Gson().fromJson(content, T::class.java)19 })2021suspend inline fun Request.raw() =22 awaitStringResult()2324class UserService {25 init {26 FuelManager.instance.basePath = "https://enigmatic-hollows-35001.herokuapp.com/"27 }2829 suspend fun getUsers() = withContext(Dispatchers.IO) {30 Fuel31 .get("/user")32 /**33 * TODO: Request.to() not work, fix it.34 *35 * https://stackoverflow.com/questions/57963799/reified-generic-parameter-inside-coroutine-is-not-working36 *37 * List<User> not work, use Array<User>38 * https://stackoverflow.com/a/6040154839 */40 .awaitObjectResult<Array<User>>(object : ResponseDeserializable<Array<User>> {41 override fun deserialize(content: String) = Gson().fromJson(content, Array<User>::class.java)42 })43 }4445 suspend fun createUser() = withContext(Dispatchers.IO) {46 Fuel47 .post("/user")48 .body("{\"action\": \"CREATE\"}")49 .set("Content-Type", "application/json")50 .to<User>()51 }5253 suspend fun like(from: ID, to: ID) = Fuel54 .post("/user")55 .body("{\"action\": \"LIKE\", \"from\": \"$from\", \"to\":\"$to\"}")56 .set("Content-Type", "application/json")57 .raw()585960 suspend fun getChats(room_id: String) =61 Fuel.get("/chat/$room_id")62 .awaitObjectResult<Array<Chat>>(object : ResponseDeserializable<Array<Chat>> {63 override fun deserialize(content: String) = Gson().fromJson(content, Array<Chat>::class.java)})6465 suspend fun chat(room_id: String, from: ID, message: String) =66 Fuel.post("/chat/$room_id")67 .body("{\"message\":\"$message\", \"from\": \"$from\"}")68 .set("Content-Type", "application/json")69 .raw()7071}
...
FuelLiveData.kt
Source:FuelLiveData.kt
1package com.github.kittinunf.fuel.livedata2import android.arch.lifecycle.LiveData3import android.arch.lifecycle.MutableLiveData4import com.github.kittinunf.fuel.core.Deserializable5import com.github.kittinunf.fuel.core.FuelError6import com.github.kittinunf.fuel.core.Request7import com.github.kittinunf.fuel.core.Response8import com.github.kittinunf.fuel.core.deserializers.ByteArrayDeserializer9import com.github.kittinunf.fuel.core.deserializers.StringDeserializer10import com.github.kittinunf.fuel.core.response11import com.github.kittinunf.result.Result12import java.nio.charset.Charset13/**14 * Created by Ihor Kucherenko on 01.06.17.15 * https://github.com/KucherenkoIhor16 */17fun Request.liveDataResponse() = liveDataResponse(ByteArrayDeserializer())18fun Request.liveDataResponseString(charset: Charset = Charsets.UTF_8) = liveDataResponse(StringDeserializer(charset))19fun <T : Any> Request.liveDataResponseObject(deserializable: Deserializable<T>) = liveDataResponse(deserializable)20private fun <T : Any> Request.liveDataResponse(deserializable: Deserializable<T>): LiveData<Pair<Response, Result<T, FuelError>>> {21 val liveData = MutableLiveData<Pair<Response, Result<T, FuelError>>>()22 val handler: (Request, Response, Result<T, FuelError>) -> Unit = { _, response, result ->23 liveData.value = response to result24 }25 response(deserializable, handler)26 return liveData27}28fun Request.liveDataBytes() = liveDataResult(ByteArrayDeserializer())29fun Request.liveDataString(charset: Charset = Charsets.UTF_8) = liveDataResult(StringDeserializer(charset))30fun <T : Any> Request.liveDataObject(deserializable: Deserializable<T>) = liveDataResult(deserializable)31private fun <T : Any> Request.liveDataResult(deserializable: Deserializable<T>): LiveData<Result<T, FuelError>> {32 val liveData = MutableLiveData<Result<T, FuelError>>()33 val handler: (Request, Response, Result<T, FuelError>) -> Unit = { _, _, result ->34 liveData.value = result35 }36 response(deserializable, handler)37 return liveData38}...
ArticleDataProvider.kt
Source:ArticleDataProvider.kt
1package com.example.mywiki.providers2import com.example.mywiki.models.Urls3import com.example.mywiki.models.WikiResult4import com.github.kittinunf.fuel.core.FuelManager5import com.github.kittinunf.fuel.core.ResponseDeserializable6import com.github.kittinunf.fuel.core.ResponseHandler7import com.github.kittinunf.fuel.core.isSuccessful8import com.github.kittinunf.fuel.httpGet9import com.google.gson.Gson10import java.io.Reader11class ArticleDataProvider12{13 init14 {15 FuelManager.instance.baseHeaders = mapOf("User-Agent" to "Tester Wikipedia")16 }17 class WikipediaDataDeserializer : ResponseDeserializable<WikiResult>18 {19 override fun deserialize(reader: Reader): WikiResult? =20 Gson().fromJson(reader, WikiResult::class.java)21 }22 fun search(term: String, skip: Int, take: Int, responseHandler: (result: WikiResult) -> Unit?)23 {24 Urls.getSearchUrl(term, skip, take).httpGet()25 .responseObject(WikipediaDataDeserializer()) { _, _, result ->26 val (data, _) = result27 responseHandler.invoke(data as WikiResult)28 }29 }30 fun getRandom(take: Int, responseHandler: (result: WikiResult) -> Unit?)31 {...
FuelExtensions.kt
Source:FuelExtensions.kt
1package com.github.windsekirun.rxsociallogin.intenal.utils2import com.github.kittinunf.fuel.core.Deserializable3import com.github.kittinunf.fuel.core.FuelError4import com.github.kittinunf.fuel.core.Request5import com.github.kittinunf.fuel.core.deserializers.StringDeserializer6import com.github.kittinunf.fuel.core.response7import com.github.kittinunf.result.Result8import io.reactivex.Single9import java.nio.charset.Charset10fun Request.toResultObservable(charset: Charset = Charsets.UTF_8) = toResultObservable(StringDeserializer(charset))11private fun <T : Any> Request.toResultObservable(deserializable: Deserializable<T>): Single<Result<T, FuelError>> =12 Single.create { emitter ->13 val (_, _, result) = response(deserializable)14 emitter.onSuccess(result)15 emitter.setCancellable { this.cancel() }16 }...
RedditApiRouting.kt
Source:RedditApiRouting.kt
1package com.worker8.redditapi.api2import com.github.kittinunf.fuel.Fuel3import com.github.kittinunf.fuel.core.Deserializable4import com.github.kittinunf.fuel.core.HeaderValues5import com.github.kittinunf.fuel.core.Parameters6import com.github.kittinunf.fuel.rx.rxObject7import com.github.kittinunf.fuel.util.FuelRouting8interface RedditApiRouting : FuelRouting {9 override val basePath: String10 get() = "https://www.reddit.com/"11 override val params: Parameters?12 get() = null13 override val body: String?14 get() = null15 override val bytes: ByteArray?16 get() = null17 override val headers: Map<String, HeaderValues>?18 get() = null19 fun <T : Any> call(deserializable: Deserializable<T>) =20 Fuel.request(this).rxObject(deserializable)21}...
FuelJson.kt
Source:FuelJson.kt
1package no.nav.helse2import com.github.kittinunf.fuel.core.Deserializable3import com.github.kittinunf.fuel.core.Request4import com.github.kittinunf.fuel.core.Response5import com.github.kittinunf.fuel.core.response6import org.json.JSONObject7class JsonDeserializer : Deserializable<JSONObject> {8 override fun deserialize(response: Response): JSONObject {9 return JSONObject(response.dataStream.bufferedReader(Charsets.UTF_8).readText())10 }11}12fun Request.responseJSON() = response(JsonDeserializer())...
Deserializable
Using AI Code Generation
1val (data, error) = result2println(data)3println(error)4val (data, error) = result5println(data)6println(error)7val (data, error) = result8println(data)9println(error)10val (data, error) = result11println(data)12println(error)13val (data, error) = result14println(data)15println(error)16val (data, error) = result17println(data)18println(error)19val (data, error) = result20println(data)21println(error)
Deserializable
Using AI Code Generation
1data class User(val id: Int, val name: String, val email: String)2fun main(args: Array<String>) {3 .responseObject<User> { request, response, result ->4 println(request)5 println(response)6 println(result)7 }8}9fun main(args: Array<String>) {10 .responseObject<List<User>> { request, response, result ->11 println(request)12 println(response)13 println(result)14 }15}16fun main(args: Array<String>) {17 .responseObject<List<User>> { request, response, result ->18 println(request)19 println(response)20 println(result)21 }22}23data class User(val id: Int, val name: String, val email: String)24fun main(args: Array<String>) {25 .responseObject<User> { request, response, result ->26 println(request)27 println(response)28 println(result)29 }30}31fun main(args: Array<String>) {32 .responseObject<List<User>> { request, response, result ->33 println(request)34 println(response)35 println(result)36 }37}38fun main(args: Array<String>) {39 .responseObject<List<User>> { request, response, result ->40 println(request)41 println(response)
Deserializable
Using AI Code Generation
1val (data, error) = result2println(data)3val (data, error) = result4println(data)5val (data, error) = result6println(data)7val (data, error) = result8println(data)9val (data, error) = result10println(data)11val (data, error) = result12println(data)13val (data, error) = result14println(data)15val (data, error) = result16println(data)
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!