How to use responseResultHandler method of com.github.kittinunf.fuel.core.requests.private class

Best Fuel code snippet using com.github.kittinunf.fuel.core.requests.private.responseResultHandler

DefaultRequest.kt

Source:DefaultRequest.kt Github

copy

Full Screen

1package com.github.kittinunf.fuel.core.requests2import com.github.kittinunf.fuel.core.Body3import com.github.kittinunf.fuel.core.BodyLength4import com.github.kittinunf.fuel.core.BodySource5import com.github.kittinunf.fuel.core.Handler6import com.github.kittinunf.fuel.core.HeaderValues7import com.github.kittinunf.fuel.core.Headers8import com.github.kittinunf.fuel.core.InterruptCallback9import com.github.kittinunf.fuel.core.Method10import com.github.kittinunf.fuel.core.Parameters11import com.github.kittinunf.fuel.core.ProgressCallback12import com.github.kittinunf.fuel.core.Request13import com.github.kittinunf.fuel.core.RequestExecutionOptions14import com.github.kittinunf.fuel.core.RequestFeatures15import com.github.kittinunf.fuel.core.ResponseDeserializable16import com.github.kittinunf.fuel.core.ResponseHandler17import com.github.kittinunf.fuel.core.ResponseResultHandler18import com.github.kittinunf.fuel.core.ResponseValidator19import com.github.kittinunf.fuel.core.ResultHandler20import com.github.kittinunf.fuel.core.Tags21import com.github.kittinunf.fuel.core.deserializers.ByteArrayDeserializer22import com.github.kittinunf.fuel.core.deserializers.StringDeserializer23import com.github.kittinunf.fuel.core.response24import java.io.ByteArrayInputStream25import java.io.File26import java.io.FileInputStream27import java.io.InputStream28import java.net.URL29import java.net.URLConnection30import java.nio.charset.Charset31import kotlin.reflect.KClass32data class DefaultRequest(33 override val method: Method,34 override var url: URL,35 override val headers: Headers = Headers(),36 override var parameters: Parameters = listOf(),37 internal var _body: Body = DefaultBody(),38 override val enabledFeatures: RequestFeatures = mutableMapOf(),39 private val tags: Tags = mutableMapOf()40) : Request {41 override lateinit var executionOptions: RequestExecutionOptions42 override val body: Body get() = _body43 /**44 * Get the current values of the header, after normalisation of the header45 * @param header [String] the header name46 * @return the current values (or empty if none)47 */48 override operator fun get(header: String): HeaderValues {49 return headers[header]50 }51 /**52 * Set the values of the header, overriding what's there, after normalisation of the header53 *54 * @param header [String] the header name55 * @param values [Collection<*>] the values to be transformed through #toString56 * @return self57 */58 override operator fun set(header: String, values: Collection<*>): Request {59 headers[header] = values.map { it.toString() }60 return request61 }62 /**63 * Set the value of the header, overriding what's there, after normalisation of the header64 *65 * @param header [String] the header name66 * @param value [Any] the value to be transformed through #toString67 */68 override operator fun set(header: String, value: Any): Request {69 when (value) {70 is Collection<*> -> this[header] = value71 else -> headers[header] = value.toString()72 }73 return request74 }75 /**76 * Get the current values77 *78 * @see get(header: String)79 * @return [HeaderValues] the current values80 */81 override fun header(header: String) = get(header)82 /**83 * Replace the headers with the map provided84 *85 * @note In earlier versions the mapOf variant of this function worked differently than the vararg pairs variant,86 * which has been changed to make any call to header(...) always overwrite the values and any call to87 * appendHeader(...) will try to append the value.88 *89 * @see set(header: String, values: Collection<*>)90 * @see set(header: String, value: Any)91 *92 * @param map [Map<String, Any>] map of headers to replace. Value can be a list or single value93 * @return [Request] the modified request94 */95 override fun header(map: Map<String, Any>): Request {96 headers.putAll(Headers.from(map))97 return request98 }99 /**100 * Replace the headers with the pairs provided101 *102 * @note In earlier versions the mapOf variant of this function worked differently than the vararg pairs variant,103 * which has been changed to make any call to header(...) always overwrite the values and any call to104 * appendHeader(...) will try to append the value.105 *106 * @see set(header: String, values: Collection<*>)107 * @see set(header: String, value: Any)108 *109 * @param pairs [Pair<String, Any>] map of headers to replace. Value can be a list or single value110 * @return [Request] the modified request111 */112 override fun header(vararg pairs: Pair<String, Any>): Request {113 headers.putAll(Headers.from(*pairs))114 return request115 }116 /**117 * Replace the header with the provided values118 *119 * @see set(header: String, values: Collection<*>)120 *121 * @param header [String] the header to set122 * @param values [List<Any>] the values to set the header to123 * @return [Request] the modified request124 */125 override fun header(header: String, values: Collection<*>) = set(header, values)126 /**127 * Replace the header with the provided value128 *129 * @see set(header: String, values: List<Any>)130 *131 * @param header [String] the header to set132 * @param value [Any] the value to set the header to133 * @return [Request] the modified request134 */135 override fun header(header: String, value: Any): Request = set(header, value)136 /**137 * Replace the header with the provided values138 *139 * @see set(header: String, values: List<Any>)140 *141 * @param header [String] the header to set142 * @param values [Any] the values to set the header to143 * @return [Request] the modified request144 */145 override fun header(header: String, vararg values: Any) = set(header, values.toList())146 /**147 * Appends the value to the header or sets it if there was none yet148 *149 * @param header [String] the header name to append to150 * @param value [Any] the value to be transformed through #toString151 */152 override fun appendHeader(header: String, value: Any): Request {153 headers.append(header, value)154 return request155 }156 /**157 * Appends the value to the header or sets it if there was none yet158 *159 * @param header [String] the header name to append to160 * @param values [Any] the value to be transformed through #toString161 */162 override fun appendHeader(header: String, vararg values: Any): Request {163 headers.append(header, values.toList())164 return request165 }166 /**167 * Append each pair, using the key as header name and value as header content168 *169 * @param pairs [Pair<String, Any>]170 */171 override fun appendHeader(vararg pairs: Pair<String, Any>): Request {172 pairs.forEach { pair -> appendHeader(pair.first, pair.second) }173 return request174 }175 /**176 * Sets the body to be read from a generic body source.177 *178 * @note in earlier versions the body callback would be called multiple times in order to maybe get the size. But179 * that would lead to closed streams being unable to be read. If the size is known, set it before anything else.180 *181 * @param openStream [BodySource] a function that yields a stream182 * @param calculateLength [Number?] size in +bytes+ if it is known183 * @param charset [Charset] the charset to write with184 * @param repeatable [Boolean] loads the body into memory upon reading185 *186 * @return [Request] the request187 */188 override fun body(openStream: BodySource, calculateLength: BodyLength?, charset: Charset, repeatable: Boolean): Request {189 _body = DefaultBody190 .from(openStream = openStream, calculateLength = calculateLength, charset = charset)191 .let { body -> if (repeatable) body.asRepeatable() else body }192 return request193 }194 /**195 * Sets the body from a generic stream196 *197 * @note the stream will be read from the position it's at. Make sure you rewind it if you want it to be read from198 * the start.199 *200 * @param stream [InputStream] a stream to read from201 * @param calculateLength [Number?] size in bytes if it is known202 * @param charset [Charset] the charset to write with203 * @param repeatable [Boolean] loads the body into memory upon reading204 *205 * @return [Request] the request206 */207 override fun body(stream: InputStream, calculateLength: BodyLength?, charset: Charset, repeatable: Boolean) =208 body(openStream = { stream }, calculateLength = calculateLength, charset = charset, repeatable = repeatable)209 /**210 * Sets the body from a byte array211 *212 * @param bytes [ByteArray] the bytes to write213 * @param charset [Charset] the charset to write with214 * @return [Request] the request215 */216 override fun body(bytes: ByteArray, charset: Charset) =217 body(stream = ByteArrayInputStream(bytes), calculateLength = { bytes.size.toLong() }, charset = charset, repeatable = true)218 /**219 * Sets the body from a string220 *221 * @param body [String] the string to write222 * @param charset [Charset] the charset to write with223 * @return [Request] the request224 */225 override fun body(body: String, charset: Charset): Request =226 body(bytes = body.toByteArray(charset), charset = charset)227 .let {228 if (header(Headers.CONTENT_TYPE).lastOrNull().isNullOrBlank())229 header(Headers.CONTENT_TYPE, "text/plain; charset=${charset.name()}")230 else it231 }232 /**233 * Sets the body to the contents of a file.234 *235 * @note this does *NOT* make this a multipart upload. For that you can use the upload request. This function can be236 * used if you want to upload the single contents of a text based file as an inline body.237 *238 * @note when charset is not UTF-8, this forces the client to use chunked encoding, because file.length() gives the239 * length of the file in bytes without considering the charset. If the charset is to be considered, the file needs240 * to be read in its entirety which defeats the purpose of using a file.241 *242 * @param file [File] the file to write to the body243 * @param charset [Charset] the charset to write with244 * @return [Request] the request245 */246 override fun body(file: File, charset: Charset): Request = when (charset) {247 Charsets.UTF_8 -> body({ FileInputStream(file) }, { file.length() }, charset)248 else -> body({ FileInputStream(file) }, null, charset)249 }.let {250 if (header(Headers.CONTENT_TYPE).lastOrNull().isNullOrBlank()) {251 val contentType = URLConnection.guessContentTypeFromName(file.name)252 header(Headers.CONTENT_TYPE, "$contentType; charset=${charset.name()}")253 } else {254 it255 }256 }257 /**258 * Sets the body to a defined [Body]259 *260 * @param body [Body] the body to assign261 * @return [Request] the request262 */263 override fun body(body: Body): Request {264 _body = body265 return request266 }267 /**268 * Add a [ProgressCallback] tracking the [Body] of the [Request]269 *270 * @see body271 * @see com.github.kittinunf.fuel.core.requests.UploadRequest.progress272 *273 * @return self274 */275 override fun requestProgress(handler: ProgressCallback): Request {276 executionOptions.requestProgress += handler277 return request278 }279 /**280 * Add a [ProgressCallback] tracking the [Body] of the [com.github.kittinunf.fuel.core.Response]281 *282 * @see com.github.kittinunf.fuel.core.requests.DownloadRequest.progress283 *284 * @return self285 */286 override fun responseProgress(handler: ProgressCallback): Request {287 executionOptions.responseProgress += handler288 return request289 }290 /**291 * Add a [InterruptCallback] to the [RequestExecutionOptions]292 *293 * @see RequestExecutionOptions.interruptCallbacks294 *295 * @return self296 */297 override fun interrupt(interrupt: InterruptCallback) = request.also {298 it.executionOptions.interruptCallbacks.plusAssign(interrupt)299 }300 /**301 * Overwrite the [Request] [timeout] in milliseconds302 *303 * @note [com.github.kittinunf.fuel.core.Client] must implement this behaviour304 * @note the default client sets [java.net.HttpURLConnection.setConnectTimeout]305 *306 * @param timeout [Int] timeout in milliseconds307 * @return self308 */309 override fun timeout(timeout: Int) = request.also {310 it.executionOptions.timeoutInMillisecond = timeout311 }312 /**313 * Overwrite the [Request] [timeout] in milliseconds314 *315 * @note [com.github.kittinunf.fuel.core.Client] must implement this behaviour316 * @note the default client sets [java.net.HttpURLConnection.setReadTimeout]317 *318 * @param timeout [Int] timeout in milliseconds319 * @return self320 */321 override fun timeoutRead(timeout: Int) = request.also {322 it.executionOptions.timeoutReadInMillisecond = timeout323 }324 /**325 * Follow redirects as handled by instances of RedirectInterceptors326 * i.e. [com.github.kittinunf.fuel.core.interceptors.redirectResponseInterceptor]327 *328 * @note The interceptor must implement this behaviour329 * @note The provided RedirectResponseInterceptor defaults to true330 *331 * @param allowRedirects [Boolean] true if allowing, false if not332 * @return self333 */334 override fun allowRedirects(allowRedirects: Boolean) = request.also {335 it.executionOptions.allowRedirects = allowRedirects336 }337 /**338 * Overwrite [RequestExecutionOptions] http cache usage flag339 *340 * @note [com.github.kittinunf.fuel.core.Client] must implement this behaviour341 * @note The default client sends `Cache-Control: none` if this flag is false, defaults to true342 *343 * @see java.net.HttpURLConnection.setUseCaches344 * @param useHttpCache [Boolean] true if suggest client to allow cached responses, false otherwise345 */346 override fun useHttpCache(useHttpCache: Boolean) = request.also {347 it.executionOptions.useHttpCache = useHttpCache348 }349 /**350 * Overwrite [RequestExecutionOptions] response validator block351 *352 * @note The default responseValidator is to throw [com.github.kittinunf.fuel.core.HttpException]353 * @note if the response http status code is not in the range of (100 - 399) which should consider as failure response354 *355 * @param validator [ResponseValidator]356 * @return [Request] the modified request357 */358 override fun validate(validator: ResponseValidator) = request.also {359 it.executionOptions.responseValidator = validator360 }361 /**362 * Attach tag to the request363 *364 * @note tag is a generic purpose tagging for Request. This can be used to attach arbitrarily object to the Request instance.365 * @note Tags internally is represented as hashMap that uses class as a key.366 *367 * @param t [Any]368 * @return [Request] the modified request369 */370 override fun tag(t: Any) = request.also {371 tags[t::class] = t372 }373 /**374 * Return corresponding tag from the request375 *376 * @note tag is a generic purpose tagging for Request. This can be used to attach arbitrarily object to the Request instance.377 * @note Tags internally is represented as hashMap that uses class as a key.378 *379 * @param clazz [KClass]380 * @return [Any] previously attached tag if any, null otherwise381 */382 override fun <T : Any> getTag(clazz: KClass<T>) = tags[clazz] as? T383 override val request: Request get() = this384 /**385 * Returns a string representation of the request.386 *387 * @see com.github.kittinunf.fuel.core.extensions.httpString388 * @see com.github.kittinunf.fuel.core.extensions.cUrlString389 *390 * @return [String] the string representation391 */392 override fun toString(): String = buildString {393 appendln("--> $method $url")394 appendln("Body : ${body.asString(header(Headers.CONTENT_TYPE).lastOrNull())}")395 appendln("Headers : (${headers.size})")396 val appendHeaderWithValue = { key: String, value: String -> appendln("$key : $value") }397 headers.transformIterate(appendHeaderWithValue)398 }399 override fun response(handler: ResponseResultHandler<ByteArray>) =400 response(ByteArrayDeserializer(), handler)401 override fun response(handler: ResultHandler<ByteArray>) =402 response(ByteArrayDeserializer(), handler)403 override fun response(handler: ResponseHandler<ByteArray>) =404 response(ByteArrayDeserializer(), handler)405 override fun response(handler: Handler<ByteArray>) =406 response(ByteArrayDeserializer(), handler)407 override fun response() =408 response(ByteArrayDeserializer())409 override fun responseString(charset: Charset, handler: ResponseResultHandler<String>) =410 response(StringDeserializer(charset), handler)411 override fun responseString(handler: ResponseResultHandler<String>) =412 responseString(Charsets.UTF_8, handler)413 override fun responseString(charset: Charset, handler: ResultHandler<String>) =414 response(StringDeserializer(charset), handler)415 override fun responseString(handler: ResultHandler<String>) =416 responseString(Charsets.UTF_8, handler)417 override fun responseString(charset: Charset, handler: ResponseHandler<String>) =418 response(StringDeserializer(charset), handler)419 override fun responseString(handler: ResponseHandler<String>) =420 response(StringDeserializer(), handler)421 override fun responseString(charset: Charset, handler: Handler<String>) =422 response(StringDeserializer(charset), handler)423 override fun responseString(handler: Handler<String>) =424 response(StringDeserializer(), handler)425 override fun responseString(charset: Charset) =426 response(StringDeserializer(charset))427 override fun responseString() = response(StringDeserializer(Charsets.UTF_8))428 override fun <T : Any> responseObject(deserializer: ResponseDeserializable<T>, handler: ResponseResultHandler<T>) =429 response(deserializer, handler)430 override fun <T : Any> responseObject(deserializer: ResponseDeserializable<T>, handler: ResultHandler<T>) =431 response(deserializer, handler)432 override fun <T : Any> responseObject(deserializer: ResponseDeserializable<T>, handler: ResponseHandler<T>) =433 response(deserializer, handler)434 override fun <T : Any> responseObject(deserializer: ResponseDeserializable<T>, handler: Handler<T>) =435 response(deserializer, handler)436 override fun <T : Any> responseObject(deserializer: ResponseDeserializable<T>) =437 response(deserializer)438}...

Full Screen

Full Screen

Deserializable.kt

Source:Deserializable.kt Github

copy

Full Screen

1package com.github.kittinunf.fuel.core2import com.github.kittinunf.fuel.Fuel3import com.github.kittinunf.fuel.core.deserializers.EmptyDeserializer4import com.github.kittinunf.fuel.core.requests.CancellableRequest5import com.github.kittinunf.fuel.core.requests.DefaultBody6import com.github.kittinunf.fuel.core.requests.RequestTaskCallbacks7import com.github.kittinunf.fuel.core.requests.suspendable8import com.github.kittinunf.fuel.core.requests.toTask9import com.github.kittinunf.result.Result10import com.github.kittinunf.result.getOrElse11import com.github.kittinunf.result.map12import com.github.kittinunf.result.mapError13import java.io.InputStream14import java.io.Reader15import kotlin.jvm.Throws16/**17 * Generic interface for [Response] deserialization.18 *19 * @note you are responsible of using the [Response] [Body] [InputStream] and closing it when you're done. Failing to do20 * so can result in hanging connections if used in conjunction with [com.github.kittinunf.fuel.toolbox.HttpClient].21 *22 * @see ResponseDeserializable23 */24interface Deserializable<out T : Any> {25 /**26 * Deserialize [response] into [T]27 *28 * @param response [Response] the incoming response29 * @return [T] the instance of [T]30 */31 fun deserialize(response: Response): T32}33interface ResponseDeserializable<out T : Any> : Deserializable<T> {34 override fun deserialize(response: Response): T {35 response.body.toStream().use { stream ->36 return deserialize(stream)37 ?: deserialize(stream.reader())38 ?: reserialize(response, stream).let {39 deserialize(response.data)40 ?: deserialize(String(response.data))41 ?: throw FuelError.wrap(IllegalStateException(42 "One of deserialize(ByteArray) or deserialize(InputStream) or deserialize(Reader) or " +43 "deserialize(String) must be implemented"44 ))45 }46 }47 }48 private fun reserialize(response: Response, stream: InputStream): Response {49 val length = response.body.length50 response.body = DefaultBody.from({ stream }, length?.let { l -> { l } })51 return response52 }53 /**54 * Deserialize into [T] from an [InputStream]55 *56 * @param inputStream [InputStream] source bytes57 * @return [T] deserialized instance of [T] or null when not applied58 */59 fun deserialize(inputStream: InputStream): T? = null60 /**61 * Deserialize into [T] from a [Reader]62 *63 * @param reader [Reader] source bytes64 * @return [T] deserialized instance of [T] or null when not applied65 */66 fun deserialize(reader: Reader): T? = null67 /**68 * Deserialize into [T] from a [ByteArray]69 *70 * @note it is more efficient to implement the [InputStream] variant.71 *72 * @param bytes [ByteArray] source bytes73 * @return [T] deserialized instance of [T] or null when not applied74 */75 fun deserialize(bytes: ByteArray): T? = null76 /**77 * Deserialize into [T] from a [String]78 *79 * @note it is more efficient to implement the [Reader] variant.80 *81 * @param content [String] source bytes82 * @return [T] deserialized instance of [T] or null when not applied83 */84 fun deserialize(content: String): T? = null85}86/**87 * Deserialize the [Response] to the [this] into a [T] using [U]88 *89 * @see ResponseResultHandler90 *91 * @param deserializable [U] the instance that performs deserialization92 * @param handler [ResponseResultHandler<T>] handler that has a [Result]93 * @return [CancellableRequest] the request that can be cancelled94 */95fun <T : Any, U : Deserializable<T>> Request.response(deserializable: U, handler: ResponseResultHandler<T>): CancellableRequest =96 response(deserializable,97 { request, response, value -> handler(request, response, Result.Success(value)) },98 { request, response, error -> handler(request, response, Result.Failure(error)) }99 )100/**101 * Deserialize the [Response] to the [this] into a [T] using [U]102 *103 * @see ResultHandler104 *105 * @param deserializable [U] the instance that performs deserialization106 * @param handler [ResultHandler<T>] handler that has a [Result]107 * @return [CancellableRequest] the request that can be cancelled108 */109fun <T : Any, U : Deserializable<T>> Request.response(deserializable: U, handler: ResultHandler<T>): CancellableRequest =110 response(deserializable,111 { _, _, value -> handler(Result.Success(value)) },112 { _, _, error -> handler(Result.Failure(error)) }113 )114/**115 * Deserialize the [Response] to the [this] into a [T] using [U]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 )206 return CancellableRequest.enableFor(this, future = executionOptions.submit(asyncRequest))207}208/**209 * Await [T] or throws [FuelError]210 * @return [T] the [T]211 */212@Throws(FuelError::class)213suspend fun <T : Any, U : Deserializable<T>> Request.await(deserializable: U): T {214 val response = suspendable().await()215 return runCatching { deserializable.deserialize(response) }216 .onFailure { throw FuelError.wrap(it, response) }217 .getOrThrow()218}219/**220 * Await the task or throws [FuelError] in current coroutine context.221 *222 * Use this method to avoid huge memory allocation when using [com.github.kittinunf.fuel.core.requests.download]223 * to a large file without using response result224 *225 * To run method in different coroutine context, use `com.github.kittinunf.fuel.coroutines.awaitUnit` in `fuel-coroutines` module226 */227@Throws(FuelError::class)228suspend fun Request.awaitUnit(): Unit = await(EmptyDeserializer)229/**230 * Await [T] or [FuelError]231 * @return [ResponseOf<T>] the [Result] of [T]232 */233@Throws(FuelError::class)234suspend fun <T : Any, U : Deserializable<T>> Request.awaitResponse(deserializable: U): ResponseOf<T> {235 val response = suspendable().await()236 return runCatching { Triple(this, response, deserializable.deserialize(response)) }237 .onFailure { throw FuelError.wrap(it, response) }238 .getOrThrow()239}240/**241 * Await [T] or [FuelError]242 * @return [Result<T>] the [Result] of [T]243 */244suspend fun <T : Any, U : Deserializable<T>> Request.awaitResult(deserializable: U): Result<T, FuelError> {245 val initialResult = suspendable().awaitResult()246 return serializeFor(initialResult, deserializable).map { (_, t) -> t }247}248/**249 * Await [T] or [FuelError]250 * @return [ResponseResultOf<T>] the [ResponseResultOf] of [T]251 */252suspend fun <T : Any, U : Deserializable<T>> Request.awaitResponseResult(deserializable: U): ResponseResultOf<T> {253 val initialResult = suspendable().awaitResult()254 return serializeFor(initialResult, deserializable).let {255 Triple(this,256 it.fold({ (response, _) -> response }, { error -> error.response }),257 it.map { (_, t) -> t }258 )259 }260}261private fun <T : Any, U : Deserializable<T>> serializeFor(result: Result<Response, FuelError>, deserializable: U) =262 result.map { (it to deserializable.deserialize(it)) }263 .mapError <Pair<Response, T>, Exception, FuelError> {264 FuelError.wrap(it, result.getOrElse { Response.error() })265 }...

Full Screen

Full Screen

ObjectTest.kt

Source:ObjectTest.kt Github

copy

Full Screen

...118 })119 running.join()120 }121 @Test122 fun responseResultHandler() {123 val uuid = randomUUID()124 val running = getUUID(uuid).response(UUIDResponseDeserializer) { result: Result<UUIDResponse, FuelError> ->125 val (data, error) = result126 assertThat("Expected data, actual error $error", data, notNullValue())127 assertThat(data!!.uuid, equalTo(uuid.toString()))128 }129 running.join()130 }131 @Test132 fun responseResultHandlerFailure() {133 val running = mocked404().response(UUIDResponseDeserializer) { result: Result<UUIDResponse, FuelError> ->134 val (data, error) = result135 assertThat("Expected error, actual data $data", error, notNullValue())136 }137 running.join()138 }139 @Test140 fun responseResponseResultHandler() {141 val uuid = randomUUID()142 val running = getUUID(uuid).response(UUIDResponseDeserializer) { request, response, result ->143 val (data, error) = result144 assertThat("Expected data, actual error $error", data, notNullValue())145 assertThat(data!!.uuid, equalTo(uuid.toString()))146 assertThat("Expected request to be not null", request, notNullValue())...

Full Screen

Full Screen

StringTest.kt

Source:StringTest.kt Github

copy

Full Screen

...106 })107 running.join()108 }109 @Test110 fun responseResultHandler() {111 val string = randomString()112 val running = getString(string).responseString { result: Result<String, FuelError> ->113 val (data, error) = result114 assertThat("Expected data, actual error $error", data, notNullValue())115 assertThat(data, equalTo(string))116 }117 running.join()118 }119 @Test120 fun responseResultHandlerFailure() {121 val running = mocked404().responseString { result: Result<String, FuelError> ->122 val (data, error) = result123 assertThat("Expected error, actual data $data", error, notNullValue())124 }125 running.join()126 }127 @Test128 fun responseResponseResultHandler() {129 val string = randomString()130 val running = getString(string).responseString { request, response, result ->131 val (data, error) = result132 assertThat("Expected data, actual error $error", data, notNullValue())133 assertThat(data, equalTo(string))134 assertThat("Expected request to be not null", request, notNullValue())...

Full Screen

Full Screen

ByteArrayTest.kt

Source:ByteArrayTest.kt Github

copy

Full Screen

...106 })107 running.join()108 }109 @Test110 fun responseResultHandler() {111 val bytes = randomBytes()112 val running = getBytes(bytes).response { result: Result<ByteArray, FuelError> ->113 val (data, error) = result114 assertThat("Expected data, actual error $error", data, notNullValue())115 assertThat(data, equalTo(bytes))116 }117 running.join()118 }119 @Test120 fun responseResultHandlerFailure() {121 val running = mocked404().response { result: Result<ByteArray, FuelError> ->122 val (data, error) = result123 assertThat("Expected error, actual data $data", error, notNullValue())124 }125 running.join()126 }127 @Test128 fun responseResponseResultHandler() {129 val bytes = randomBytes()130 val running = getBytes(bytes).response { request, response, result ->131 val (data, error) = result132 assertThat("Expected data, actual error $error", data, notNullValue())133 assertThat(data, equalTo(bytes))134 assertThat("Expected request to be not null", request, notNullValue())...

Full Screen

Full Screen

responseResultHandler

Using AI Code Generation

copy

Full Screen

1 .responseResultHandler { request, response, result ->2 }3 .responseResultHandler { request, response, result ->4 }5 .responseResultHandler { request, response, result ->6 }7 .responseResultHandler { request, response, result ->8 }9 .responseResultHandler { request, response, result ->10 }11 .responseResultHandler { request, response, result ->12 }13 .responseResultHandler { request, response, result ->14 }15 .responseResultHandler { request, response, result ->16 }

Full Screen

Full Screen

responseResultHandler

Using AI Code Generation

copy

Full Screen

1fun <T : Any> Request.responseResultHandler(deserializer: ResponseDeserializable<T>, handler: (Request, Response, Result<T, FuelError>) -> Unit): Request {2val responseDeserializer = ResponseResultDeserializer(deserializer)3response(responseDeserializer) { request, response, result ->4handler(request, response, result)5}6}7result.fold({ data ->8println(data)9}, { error ->10println(error)11})12}

Full Screen

Full Screen

responseResultHandler

Using AI Code Generation

copy

Full Screen

1val (_, _, result) = Fuel.get("/hello").responseResultHandler { request, response, result ->2println("Request: $request")3println("Response: $response")4println("Result: $result")5}6println("Result: $result")7println("Result: ${result.get()}")8val (_, _, result) = Fuel.get("/hello").responseResultHandler { request, response, result ->9println("Request: $request")10println("Response: $response")11println("Result: $result")12}13println("Result: $result")14println("Result: ${result.get()}")15val (_, _, result) = Fuel.get("/hello").responseResultHandler { request, response, result ->16 println("Request: $request")17 println("Response: $response")18 println("Result: $result")19}20println("Result: $result")21println("Result: ${result.get()}")22Result: Success(text/plain; charset=utf-8, 12 bytes)23Result: Success(text/plain; charset=utf-8, 12 bytes)24Success(text/plain; charset=utf-8, 12 bytes)25Success(text/plain; charset=utf-8, 12 bytes)

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful