Best Fuel code snippet using com.github.kittinunf.fuel.core.requests.private.success
Deserializable.kt
Source:Deserializable.kt  
...116 *117 * @see ResponseHandler118 *119 * @param deserializable [U] the instance that performs deserialization120 * @param handler [ResponseHandler<T>] handler that has dedicated paths for success and failure121 * @return [CancellableRequest] the request that can be cancelled122 */123fun <T : Any, U : Deserializable<T>> Request.response(deserializable: U, handler: ResponseHandler<T>): CancellableRequest =124    response(deserializable,125        { request, response, value -> handler.success(request, response, value) },126        { request, response, error -> handler.failure(request, response, error) }127    )128/**129 * Deserialize the [Response] to the [this] into a [T] using [U]130 *131 * @see Handler132 *133 * @param deserializable [U] the instance that performs deserialization134 * @param handler [Handler<T>] handler that has dedicated paths for success and failure135 * @return [CancellableRequest] the request that can be cancelled136 */137fun <T : Any, U : Deserializable<T>> Request.response(deserializable: U, handler: Handler<T>): CancellableRequest =138    response(deserializable,139        { _, _, value -> handler.success(value) },140        { _, _, error -> handler.failure(error) }141    )142/**143 * Deserialize the [Response] to the [this] into a [T] using [U]144 *145 * @note not async, use the variations with a handler instead.146 *147 * @throws Exception if there is an internal library error, not related to Network or Deserialization148 *149 * @param deserializable [U] the instance that performs deserialization150 * @return [ResponseResultOf<T>] the response result of151 */152fun <T : Any, U : Deserializable<T>> Request.response(deserializable: U): ResponseResultOf<T> {153    // First execute the network request and catch any issues154    val rawResponse = runCatching { toTask().call() }155        .onFailure { error ->156            FuelError.wrap(error, Response.error(url)).also {157                return Triple(this, it.response, Result.error(it))158            }159        }160        .getOrThrow()161    // By this time it should have a response, but deserialization might fail162    return runCatching { Triple(this, rawResponse, Result.Success(deserializable.deserialize(rawResponse))) }163        .recover { error -> Triple(this, rawResponse, Result.Failure(FuelError.wrap(error, rawResponse))) }164        .getOrThrow()165}166/**167 * Ignore the response result168 *169 * Use this method to avoid huge memory allocation when using [com.github.kittinunf.fuel.core.requests.download]170 * to a large download and without using the result [ByteArray]171 *172 * @see [com.github.kittinunf.fuel.core.Request.response]173 *174 * @note not async, use the variations with a handler instead.175 *176 * @throws Exception if there is an internal library error, not related to Network177 */178fun Request.responseUnit(): ResponseResultOf<Unit> = response(EmptyDeserializer)179private fun <T : Any, U : Deserializable<T>> Request.response(180    deserializable: U,181    success: (Request, Response, T) -> Unit,182    failure: (Request, Response, FuelError) -> Unit183): CancellableRequest {184    val asyncRequest = RequestTaskCallbacks(185        request = this,186        onSuccess = { response ->187            // The network succeeded but deserialization might fail188            val deliverable = Result.of<T, Exception> { deserializable.deserialize(response) }189            executionOptions.callback {190                deliverable.fold(191                    { success(this, response, it) },192                    { failure(this, response, FuelError.wrap(it, response).also { error ->193                        Fuel.trace { "[Deserializable] unfold failure: \n\r$error" } })194                    }195                )196            }197        },198        onFailure = { error, response ->199            executionOptions.callback {200                failure(this, response, error.also { error ->201                    Fuel.trace { "[Deserializable] callback failure: \n\r$error" }202                })203            }204        }205    )...ShuRemoteDefault.kt
Source:ShuRemoteDefault.kt  
...42        var headersImpl: ((Decoder<*>) -> Headers?)? = null43        var requestBarrierImpl: (suspend (Decoder<*>) -> Unit)? = null44        var validateResponseImpl: ((ShuRawResponse) -> Unit)? = null45        var recoverImpl: (suspend (Decoder<*>, Throwable) -> Unit)? = null46        var successImpl: ((ShuResponse<*>) -> Unit)? = null47        override fun headers(block: (Decoder<*>) -> Headers?) {48            headersImpl = block49        }50        override fun requestBarrier(block: suspend (Decoder<*>) -> Unit) {51            requestBarrierImpl = block52        }53        override fun validateResponse(block: (ShuRawResponse) -> Unit) {54            validateResponseImpl = block55        }56        override fun recover(block: suspend (Decoder<*>, Throwable) -> Unit) {57            recoverImpl = block58        }59        override fun success(block: (ShuResponse<*>) -> Unit) {60            successImpl = block61        }62    }63    private val middlewares = mutableListOf<MiddlewareImpl>()64    override fun addMiddleware(block: Middleware.() -> Unit) {65        middlewares.add(MiddlewareImpl().also(block))66    }67    private fun validateWithMiddlewares(response: Response) {68        val shuResponse = response.asShu()69        middlewares.mapNotNull { it.validateResponseImpl }.forEach { it(shuResponse) }70    }71    private fun fullUrl(path: String, query: QueryParameters? = null): String {72        val url = URI("$apiUrl/$path")73        val urlPath = url.path?.replace(Regex("/+"), "/") ?: ""74        val newUrl = with(url) {75            val newQuery = listOfNotNull(this.query, query?.uriQueryString()).takeIf { it.isNotEmpty() }?.joinToString("&")76            URI(scheme, userInfo, host, port, urlPath, newQuery, fragment)77        }78        return newUrl.toString()79    }80    private suspend fun <T : Any> runRequest(request: Request, decoder: Decoder<T>, context: StackTraceElement?): ShuResponse<T> = coroutineScope {81        val requestJob = async {82            val (result, response) = request.response(decoder, context)83            ShuResponse(result, response.asShu())84        }85        requestJob.invokeOnCompletion {86            if (it !is CancellationException) return@invokeOnCompletion87            request.tryCancel()88        }89        requestJob.await()90    }91    override suspend fun <RequestType : Any, ResponseType : Any> request(operation: ShuOperation<RequestType, ResponseType>, context: StackTraceElement?): Result<ShuResponse<ResponseType>> =92        Result.of {93            with(operation) {94                val body = when (method) {95                    GET, DELETE -> null96                    POST, PUT -> resourceForSend?.let { requestEncoder().encode(it) }97                    else -> throw Exception("Unsupported HTTP method $method")98                }99                val decoder = responseDecoder()100                val fullUrl = fullUrl(path, queryParameters)101                makeJob(decoder) { state ->102                    val headersList = (middlewares.mapNotNull { it.headersImpl?.invoke(decoder) } + headers).filterNotNull()103                    val headers = if (headersList.isNotEmpty()) headersList.reduce { acc, map -> acc + map } else emptyMap()104                    val request = manager.request(method, fullUrl).header(headers)105                    body?.also { request.body(it) }106                    state.request = request107                    runRequest(request, decoder, context)108                }109            }110        }111    private class RequestHolder<T : ShuResponse<*>>(112        var request: Request? = null,113        var task: (RequestHolder<T>) -> Deferred<T>114    )115    private suspend fun <T : ShuResponse<M>, M : Any> makeJob(mapper: Decoder<M>, block: suspend (RequestHolder<T>) -> T): T = coroutineScope {116        val state = RequestHolder<T> {117            async {118                try {119                    checkForError(mapper) { block(it) }120                } catch (e: Throwable) {121                    it.request?.tryCancel()122                    it.task(it).cancel()123                    throw e124                }125            }126        }127        state.task(state).await()128    }129    private suspend fun <T : ShuResponse<M>, M : Any> checkForError(mapper: Decoder<M>, request: suspend () -> T): T {130        return try {131            middlewares.mapNotNull { it.requestBarrierImpl }.map { it(mapper) }132            request().also { result -> middlewares.mapNotNull { it.successImpl }.forEach { it(result) } }133        } catch (e: CancellationException) {134            throw e135        } catch (exception: Throwable) {136            val error = when (exception) {137                is FuelError -> exception.exception138                else -> exception139            }140            val results = middlewares141                .mapNotNull { it.recoverImpl }142                .map { Result.of { it(mapper, error) } }143            results144                .firstOrNull { it.isSuccess }145                ?.let {146                    checkForError(mapper, request)...App.kt
Source:App.kt  
...79                        httpRequest.body( {ByteArrayInputStream(body) })80                    }81                    val (_, response, result) = httpRequest.awaitByteArrayResponseResult()82                    result.fold(83                        { success -> call.forward(response, success)},84                        { failure ->85                            if (-1 == response.statusCode) {86                                logger.error(failure.toString())87                                call.respondErrorAndLog(HttpStatusCode.GatewayTimeout, "Unable to proxy request.")88                            } else {89                                call.forward(response, failure.errorData)90                            }91                        }92                    )93                }94            }95        }96    }97}...Reactor.kt
Source:Reactor.kt  
...19    }20private fun <T : Any> Request.monoResultFold(mapper: Deserializable<T>): Mono<T> =21    monoResult { sink ->22        response(mapper) { _, _, result ->23            result.fold(sink::success, sink::error)24        }25    }26private fun <T : Any> Request.monoResultUnFolded(mapper: Deserializable<T>): Mono<Result<T, FuelError>> =27    monoResult { sink ->28        response(mapper) { _, _, result ->29            sink.success(result)30        }31    }32/**33 * Get a single [Response]34 * @return [Mono<Response>] the [Mono]35 */36fun Request.monoResponse(): Mono<Response> =37    monoResult { sink ->38        response { _, res, _ -> sink.success(res) }39    }40/**41 * Get a single [ByteArray] via a [MonoSink.success], or any [FuelError] via [MonoSink.error]42 *43 * @see monoResultBytes44 * @return [Mono<ByteArray>] the [Mono]45 */46fun Request.monoBytes(): Mono<ByteArray> = monoResultFold(ByteArrayDeserializer())47/**48 * Get a single [String] via a [MonoSink.success], or any [FuelError] via [MonoSink.error]49 *50 * @see monoResultString51 *52 * @param charset [Charset] the charset to use for the string, defaults to [Charsets.UTF_8]53 * @return [Mono<String>] the [Mono]54 */55fun Request.monoString(charset: Charset = Charsets.UTF_8): Mono<String> = monoResultFold(StringDeserializer(charset))56/**57 * Get a single [T] via a [MonoSink.success], or any [FuelError] via [MonoSink.error]58 *59 * @see monoResultObject60 *61 * @param mapper [Deserializable<T>] the deserializable that can turn the response int a [T]62 * @return [Mono<T>] the [Mono]63 */64fun <T : Any> Request.monoObject(mapper: Deserializable<T>): Mono<T> = monoResultFold(mapper)65/**66 * Get a single [ByteArray] or [FuelError] via [Result]67 *68 * @see monoBytes69 * @return [Mono<Result<ByteArray, FuelError>>] the [Mono]70 */71fun Request.monoResultBytes(): Mono<Result<ByteArray, FuelError>> =72    monoResultUnFolded(ByteArrayDeserializer())73/**74 * Get a single [String] or [FuelError] via [Result]75 *76 * @see monoString77 *78 * @param charset [Charset] the charset to use for the string, defaults to [Charsets.UTF_8]79 * @return [Mono<Result<ByteArray, FuelError>>] the [Mono]80 */81fun Request.monoResultString(charset: Charset = Charsets.UTF_8): Mono<Result<String, FuelError>> =82    monoResultUnFolded(StringDeserializer(charset))83/**84 * Get a single [T] or [FuelError] via [Result]85 *86 * @see monoObject87 * @return [Mono<Result<T, FuelError>>] the [Mono]88 */89fun <T : Any> Request.monoResultObject(mapper: Deserializable<T>): Mono<Result<T, FuelError>> =90    monoResultUnFolded(mapper)91/**92 * Get a complete signal(success with [Unit]) via a [MonoSink.success], or any [FuelError] via [MonoSink.error]93 */94fun Request.monoUnit(): Mono<Unit> = monoResultFold(EmptyDeserializer)...Library.kt
Source:Library.kt  
...7import com.example.eqmobilework.data.LocationEvent8import com.github.kittinunf.fuel.Fuel9import com.github.kittinunf.fuel.core.Request10import com.github.kittinunf.result.failure11import com.github.kittinunf.result.success12import com.google.android.gms.location.LocationServices13import com.google.gson.Gson14import java.util.*15const val TAG = "EQLIB"16class Library {17    // Queue to store log requests and reprocess if any fails18    // This logic can be moved to a permanent storage like SQLite for the final version19    val requests: Queue<LocationEvent> = LinkedList()20    private val baseUrl = "https://httpbin.org/post"21    fun setup(): Boolean {22        return true23    }24    fun log(event: LocationEvent, process: Boolean = true) {25        requests.add(event)26        if (process)27            process()28    }29    fun log(context: Context) {30        val fusedLocationClient =31            LocationServices.getFusedLocationProviderClient(context)32        if (ActivityCompat.checkSelfPermission(33                context,34                Manifest.permission.ACCESS_FINE_LOCATION35            ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(36                context,37                Manifest.permission.ACCESS_COARSE_LOCATION38            ) != PackageManager.PERMISSION_GRANTED39        ) {40            Log.e(TAG, "Location permission not granted")41            return42        }43        fusedLocationClient.lastLocation.addOnSuccessListener {44            val event = if (it == null) {45                // user doesn't have a last know location yet46                // fallback to (0,0)47                LocationEvent(0F, 0F, ext = "empty")48            } else {49                LocationEvent(50                    lat = it.latitude.toFloat(),51                    lon = it.longitude.toFloat(),52                    ext = "empty"53                )54            }55            Log.i(TAG, "Started posting")56            log(event)57        }58    }59    fun process(callback: (() -> Unit)? = null) {60        // return, no requests available to process61        if (requests.isEmpty()) return62        val location = requests.peek()!!63        post(location).responseString { _, _, result ->64            result.success {65                Log.i(TAG, "Posted successfully")66                Log.i(TAG, it)67                // remove from queue if posting was successful68                requests.remove()69                // continue processing the rest of the queue70                process()71            }72            result.failure {73                Log.e(TAG, "Failed to post")74                Log.e(TAG, it.response.statusCode.toString())75            }76            if (callback != null) callback()77        }78    }79    private fun post(location: LocationEvent): Request {80        return Fuel.post(baseUrl).body(Gson().toJson(location))81    }...ListPlaceRepository.kt
Source:ListPlaceRepository.kt  
1package com.yoesuv.networkkotlin2.networks2import com.github.kittinunf.fuel.Fuel3import com.github.kittinunf.fuel.core.FuelError4import com.github.kittinunf.fuel.core.Request5import com.github.kittinunf.fuel.core.requests.tryCancel6import com.github.kittinunf.fuel.gson.responseObject7import com.yoesuv.networkkotlin2.data.EndPoint8import com.yoesuv.networkkotlin2.menu.listplace.models.ListPlaceModel9import com.yoesuv.networkkotlin2.utils.debugPrintStackTrace10class ListPlaceRepository {11    private lateinit var requestListPlace: Request12    fun getListPlace(onSuccess:(ListPlaceModel) -> Unit, onError:(FuelError) -> Unit) {13        requestListPlace = Fuel.get(EndPoint.LIST_PLACE).responseObject<ListPlaceModel> { _, _, result ->14            result.fold({15                onSuccess(it)16            }, {17                onError(it)18                debugPrintStackTrace(it)19            })20        }21    }22    fun cleared() {23        requestListPlace.tryCancel(true)24    }25}...GalleryRepository.kt
Source:GalleryRepository.kt  
1package com.yoesuv.networkkotlin2.networks2import com.github.kittinunf.fuel.Fuel3import com.github.kittinunf.fuel.core.FuelError4import com.github.kittinunf.fuel.core.Request5import com.github.kittinunf.fuel.core.requests.tryCancel6import com.github.kittinunf.fuel.gson.responseObject7import com.yoesuv.networkkotlin2.data.EndPoint8import com.yoesuv.networkkotlin2.menu.gallery.models.GalleryModel9import com.yoesuv.networkkotlin2.utils.debugPrintStackTrace10class GalleryRepository {11    private lateinit var requestGallery: Request12    fun getListGallery(onSuccess:(GalleryModel) -> Unit, onError:(FuelError) -> Unit) {13        requestGallery = Fuel.get(EndPoint.LIST_GALLERY).responseObject<GalleryModel> { _, _, result ->14            result.fold({15                onSuccess(it)16            }, {17                onError(it)18                debugPrintStackTrace(it)19            })20        }21    }22    fun cleared() {23        requestGallery.tryCancel(true)24    }25}...WisataRepository.kt
Source:WisataRepository.kt  
1package com.magang.kelilingapp.repository2import com.github.kittinunf.fuel.Fuel3import com.github.kittinunf.fuel.core.FuelError4import com.github.kittinunf.fuel.core.Request5import com.github.kittinunf.fuel.core.requests.tryCancel6import com.github.kittinunf.fuel.gson.responseObject7import com.magang.kelilingapp.model.Wisata8class WisataRepository {9    private var URL = "https://wisatasurabayaapi.herokuapp.com/api"10    private lateinit var requestGallery: Request11    fun getWisataList(onSuccess:(Wisata) -> Unit, onError:(FuelError) -> Unit) {12        requestGallery = Fuel.get(URL).responseObject<Wisata> { _, _, result ->13            result.fold({14                onSuccess(it)15            }, {16                onError(it)17            })18        }19    }20    fun cleared() {21        requestGallery.tryCancel(true)22    }23}...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!!
