How to use CancellableRequest class of com.github.kittinunf.fuel.core.requests package

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

RxFuel.kt

Source:RxFuel.kt Github

copy

Full Screen

...5import com.github.kittinunf.fuel.core.Response6import com.github.kittinunf.fuel.core.deserializers.ByteArrayDeserializer7import com.github.kittinunf.fuel.core.deserializers.EmptyDeserializer8import com.github.kittinunf.fuel.core.deserializers.StringDeserializer9import com.github.kittinunf.fuel.core.requests.CancellableRequest10import com.github.kittinunf.fuel.core.response11import com.github.kittinunf.result.Result12import io.reactivex.rxjava3.core.Completable13import io.reactivex.rxjava3.core.Single14import java.nio.charset.Charset15private fun <T : Any> Request.rxResponseSingle(deserializable: Deserializable<T>): Single<T> =16 rx { onSuccess, onFailure ->17 response(deserializable) { _, _, result ->18 result.fold(19 success = { t -> t.also { onSuccess(t) } },20 failure = { e -> onFailure(e) }21 )22 }23 }24private fun <T : Any> Request.rxResponsePair(deserializable: Deserializable<T>): Single<Pair<Response, T>> =25 rx { onSuccess, onFailure ->26 response(deserializable) { _, response, result ->27 result.fold(28 success = { t -> t.also { onSuccess(Pair(response, t)) } },29 failure = { e -> onFailure(e) }30 )31 }32 }33private fun <T : Any> Request.rxResponseTriple(deserializable: Deserializable<T>): Single<Triple<Request, Response, T>> =34 rx { onSuccess, onFailure ->35 response(deserializable) { request, response, result ->36 result.fold(37 success = { t -> t.also { onSuccess(Triple(request, response, t)) } },38 failure = { e -> onFailure(e) }39 )40 }41 }42private fun <T : Any> Request.rxResultSingle(deserializable: Deserializable<T>): Single<Result<T, FuelError>> =43 rx { onSuccess ->44 response(deserializable) { _, _, result ->45 onSuccess(result)46 }47 }48private fun <T : Any> Request.rxResultPair(deserializable: Deserializable<T>): Single<Pair<Response, Result<T, FuelError>>> =49 rx { onSuccess ->50 response(deserializable) { _, response, result ->51 onSuccess(response to result)52 }53 }54private fun <T : Any> Request.rxResultTriple(deserializable: Deserializable<T>): Single<Triple<Request, Response, Result<T, FuelError>>> =55 rx { onSuccess ->56 response(deserializable) { request, response, result ->57 onSuccess(Triple(request, response, result))58 }59 }60/**61 * Returns a reactive stream for a [Single] value response [ByteArray]62 *63 * @see rxBytes64 * @return [Single<ByteArray>]65 */66fun Request.rxResponse() = rxResponseSingle(ByteArrayDeserializer())67/**68 * Returns a reactive stream for a [Single] value response [ByteArray]69 *70 * @see rxBytes71 * @return [Single<Pair<Response, ByteArray>>] the [ByteArray] wrapped into a [Pair] with [Response]72 */73fun Request.rxResponsePair() = rxResponsePair(ByteArrayDeserializer())74/**75 * Returns a reactive stream for a [Single] value response [ByteArray]76 *77 * @see rxBytes78 * @return [Single<Triple<Request, Response, ByteArray>>] the [ByteArray] wrapped into a [Triple] with [Response] and [Request]79 */80fun Request.rxResponseTriple() = rxResponseTriple(ByteArrayDeserializer())81/**82 * Returns a reactive stream for a [Single] value response [String]83 *84 * @see rxString85 *86 * @param charset [Charset] the character set to deserialize with87 * @return [Single<String>]88 */89fun Request.rxResponseString(charset: Charset = Charsets.UTF_8) = rxResponseSingle(StringDeserializer(charset))90/**91 * Returns a reactive stream for a [Single] value response [String]92 *93 * @see rxString94 *95 * @param charset [Charset] the character set to deserialize with96 * @return [Single<Pair<Response, String>>] the [String] wrapped into a [Pair] with [Response]97 */98fun Request.rxResponseStringPair(charset: Charset = Charsets.UTF_8) = rxResponsePair(StringDeserializer(charset))99/**100 * Returns a reactive stream for a [Single] value response [String]101 *102 * @see rxString103 *104 * @param charset [Charset] the character set to deserialize with105 * @return [Single<Triple<Request, Response, String>>] the [String] wrapped into a [Triple] with [Response] and [Request]106 */107fun Request.rxResponseStringTriple(charset: Charset = Charsets.UTF_8) = rxResponseTriple(StringDeserializer(charset))108/**109 * Returns a reactive stream for a [Single] value response object [T]110 *111 * @see rxObject112 *113 * @param deserializable [Deserializable<T>] something that can deserialize the [Response] to a [T]114 * @return [Single<T>]115 */116fun <T : Any> Request.rxResponseObject(deserializable: Deserializable<T>) = rxResponseSingle(deserializable)117/**118 * Returns a reactive stream for a [Single] value response object [T]119 *120 * @see rxObject121 *122 * @param deserializable [Deserializable<T>] something that can deserialize the [Response] to a [T]123 * @return [Single<Pair<Response, T>>] the [T] wrapped into a [Pair] with [Response]124 */125fun <T : Any> Request.rxResponseObjectPair(deserializable: Deserializable<T>) = rxResponsePair(deserializable)126/**127 * Returns a reactive stream for a [Single] value response object [T]128 *129 * @see rxObject130 *131 * @param deserializable [Deserializable<T>] something that can deserialize the [Response] to a [T]132 * @return [Single<Triple<Request, Response, T>>] the [T] wrapped into a [Triple] with [Response] and [Request]133 */134fun <T : Any> Request.rxResponseObjectTriple(deserializable: Deserializable<T>) = rxResponseTriple(deserializable)135/**136 * Returns a reactive stream for a [Single] value result of [ByteArray]137 *138 * @see rxResponse139 * @return [Single<Result<ByteArray, FuelError>>] the [ByteArray] wrapped into a [Result]140 */141fun Request.rxBytes() = rxResultSingle(ByteArrayDeserializer())142/**143 * Returns a reactive stream for a [Single] value result of [ByteArray]144 *145 * @see rxResponse146 * @return [Single<Pair<Response, Result<ByteArray, FuelError>>>] the [ByteArray] wrapped into a [Result] together with a [Pair] with [Response]147 */148fun Request.rxBytesPair() = rxResultPair(ByteArrayDeserializer())149/**150 * Returns a reactive stream for a [Single] value result of [ByteArray]151 *152 * @see rxResponse153 * @return [Single<Triple<Request, Response, Result<ByteArray, FuelError>>>] the [ByteArray] wrapped into a [Result] together with a [Triple] with [Response] and [Request]154 */155fun Request.rxBytesTriple() = rxResultTriple(ByteArrayDeserializer())156/**157 * Returns a reactive stream for a [Single] value result of [ByteArray]158 *159 * @see rxResponseString160 *161 * @param charset [Charset] the character set to deserialize with162 * @return [Single<Result<String, FuelError>>] the [String] wrapped into a [Result]163 */164fun Request.rxString(charset: Charset = Charsets.UTF_8) = rxResultSingle(StringDeserializer(charset))165/**166 * Returns a reactive stream for a [Single] value result of [String]167 *168 * @see rxResponseString169 * @return [Single<Pair<Response, Result<String, FuelError>>>] the [String] wrapped into a [Result] together with a [Pair] with [Response]170 */171fun Request.rxStringPair(charset: Charset = Charsets.UTF_8) = rxResultPair(StringDeserializer(charset))172/**173 * Returns a reactive stream for a [Single] value result of [String]174 *175 * @see rxResponseString176 * @return [Single<Triple<Request, Response, Result<String, FuelError>>>] the [String] wrapped into a [Result] together with a [Triple] with [Response] and [Request]177 */178fun Request.rxStringTriple(charset: Charset = Charsets.UTF_8) = rxResultTriple(StringDeserializer(charset))179/**180 * Returns a reactive stream for a [Single] value result of [T]181 *182 * @see rxResponseObject183 *184 * @param deserializable [Deserializable<T>] something that can deserialize the [Response] to a [T]185 * @return [Single<Result<T, FuelError>>] the [T] wrapped into a [Result]186 */187fun <T : Any> Request.rxObject(deserializable: Deserializable<T>) = rxResultSingle(deserializable)188/**189 * Returns a reactive stream for a [Single] value result of [T]190 *191 * @see rxResponseObject192 * @return [Single<Pair<Response, Result<T, FuelError>>>] the [T] wrapped into a [Result] together with a [Pair] with [Response]193 */194fun <T : Any> Request.rxObjectPair(deserializable: Deserializable<T>) = rxResultPair(deserializable)195/**196 * Returns a reactive stream for a [Single] value result of [T]197 *198 * @see rxResponseObject199 * @return [Single<Triple<Request, Response, Result<T, FuelError>>>] the [T] wrapped into a [Result] together with a [Triple] with [Response] and [Request]200 */201fun <T : Any> Request.rxObjectTriple(deserializable: Deserializable<T>) = rxResultTriple(deserializable)202/**203 * Returns a reactive stream for a [Completable] value with complete or error signal204 */205fun Request.rxCompletable(): Completable =206 rxCompletable { onComplete, onError ->207 response(EmptyDeserializer) { _, _, result ->208 result.fold(209 success = { onComplete() },210 failure = { onError(it) }211 )212 }213 }214/**215 * Generic [Single] wrapper that executes [resultBlock] and emits its result [R] to the [Single]216 *217 * This wrapper is a [io.reactivex.Single] wrapper that uses onError to signal the error that occurs218 * in the stream. If you wish to receive an Error in the format of [com.github.kittinunf.result.Result],219 * please use [rx(Request.((R) -> Unit) -> CancellableRequest)] instead.220 *221 * @param resultBlock [() -> R] function that returns [R]222 * @return [Single] the reactive stream for a [Single] with response [R]223 */224fun <R : Any> Request.rx(resultBlock: Request.((R) -> Unit, (Throwable) -> Unit) -> CancellableRequest): Single<R> =225 Single.create { emitter ->226 val cancellableRequest = resultBlock(emitter::onSuccess, emitter::onError)227 emitter.setCancellable { cancellableRequest.cancel() }228 }229/**230 * Generic [Single] wrapper that executes [resultBlock] and emits its result [R] to the [Single]231 *232 * This wrapper is a [io.reactivex.Single] wrapper that uses onSuccess in the format of [com.github.kittinunf.result.Result]233 * as a value in the stream.234 *235 * @param resultBlock [() -> R] function that returns [R]236 * @return [Single] the reactive stream for a [Single] with response [R]237 */238fun <R : Any> Request.rx(resultBlock: Request.((R) -> Unit) -> CancellableRequest): Single<R> =239 Single.create { emitter ->240 val cancellableRequest = resultBlock(emitter::onSuccess)241 emitter.setCancellable { cancellableRequest.cancel() }242 }243/**244 * [Completable] wrapper that executes [resultBlock] and emits complete or error signal245 *246 * This wrapper is a [Completable] wrapper that uses [io.reactivex.CompletableEmitter.onError] to signal the error that occurs247 * in the stream. If you wish to receive an Error in the format of [com.github.kittinunf.result.Result],248 * please use `rxCompletable(Request.(() -> Unit) -> CancellableRequest)` instead.249 *250 * @param resultBlock functions that emits complete or error signal to [Completable]251 * @return The reactive stream [Completable] with complete or error signal252 */253fun Request.rxCompletable(resultBlock: Request.(onComplete: () -> Unit, onError: (Throwable) -> Unit) -> CancellableRequest): Completable =254 Completable.create { emitter ->255 val cancellableRequest = resultBlock(emitter::onComplete, emitter::onError)256 emitter.setCancellable { cancellableRequest.cancel() }257 }258/**259 * [Completable] wrapper that executes [resultBlock] and emits complete or error signal260 *261 * This wrapper is a [Completable] wrapper that uses [io.reactivex.CompletableEmitter.onComplete] in the format of [com.github.kittinunf.result.Result]262 * as a value in the stream.263 *264 * @param resultBlock function that emits complete signal to [Completable]265 * @return The reactive stream [Completable] with complete or error signal266 */267fun Request.rxCompletable(resultBlock: Request.(onComplete: () -> Unit) -> CancellableRequest): Completable =268 Completable.create { emitter ->269 val cancellableRequest = resultBlock(emitter::onComplete)270 emitter.setCancellable { cancellableRequest.cancel() }271 }272@Suppress("FunctionName")273@Deprecated(274 "Use Request.rxResponsePair",275 replaceWith = ReplaceWith("rxResponsePair()"),276 level = DeprecationLevel.ERROR277)278fun Request.rx_response() = rxResponsePair()279@Suppress("FunctionName")280@Deprecated(281 "Use Request.rxResponseStringPair",...

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.Reader15/**16 * Generic interface for [Response] deserialization.17 *18 * @note you are responsible of using the [Response] [Body] [InputStream] and closing it when you're done. Failing to do19 * so can result in hanging connections if used in conjunction with [com.github.kittinunf.fuel.toolbox.HttpClient].20 *21 * @see ResponseDeserializable22 */23interface Deserializable<out T : Any> {24 /**25 * Deserialize [response] into [T]26 *27 * @param response [Response] the incoming response28 * @return [T] the instance of [T]29 */30 fun deserialize(response: Response): T31}32interface ResponseDeserializable<out T : Any> : Deserializable<T> {33 override fun deserialize(response: Response): T {34 response.body.toStream().use { stream ->35 return deserialize(stream)36 ?: deserialize(stream.reader())37 ?: reserialize(response, stream).let {38 deserialize(response.data)39 ?: deserialize(String(response.data))40 ?: throw FuelError.wrap(IllegalStateException(41 "One of deserialize(ByteArray) or deserialize(InputStream) or deserialize(Reader) or " +42 "deserialize(String) must be implemented"43 ))44 }45 }46 }47 private fun reserialize(response: Response, stream: InputStream): Response {48 val length = response.body.length49 response.body = DefaultBody.from({ stream }, length?.let { l -> { l } })50 return response51 }52 /**53 * Deserialize into [T] from an [InputStream]54 *55 * @param inputStream [InputStream] source bytes56 * @return [T] deserialized instance of [T] or null when not applied57 */58 fun deserialize(inputStream: InputStream): T? = null59 /**60 * Deserialize into [T] from a [Reader]61 *62 * @param reader [Reader] source bytes63 * @return [T] deserialized instance of [T] or null when not applied64 */65 fun deserialize(reader: Reader): T? = null66 /**67 * Deserialize into [T] from a [ByteArray]68 *69 * @note it is more efficient to implement the [InputStream] variant.70 *71 * @param bytes [ByteArray] source bytes72 * @return [T] deserialized instance of [T] or null when not applied73 */74 fun deserialize(bytes: ByteArray): T? = null75 /**76 * Deserialize into [T] from a [String]77 *78 * @note it is more efficient to implement the [Reader] variant.79 *80 * @param content [String] source bytes81 * @return [T] deserialized instance of [T] or null when not applied82 */83 fun deserialize(content: String): T? = null84}85/**86 * Deserialize the [Response] to the [this] into a [T] using [U]87 *88 * @see ResponseResultHandler89 *90 * @param deserializable [U] the instance that performs deserialization91 * @param handler [ResponseResultHandler<T>] handler that has a [Result]92 * @return [CancellableRequest] the request that can be cancelled93 */94fun <T : Any, U : Deserializable<T>> Request.response(deserializable: U, handler: ResponseResultHandler<T>): CancellableRequest =95 response(deserializable,96 { request, response, value -> handler(request, response, Result.Success(value)) },97 { request, response, error -> handler(request, response, Result.Failure(error)) }98 )99/**100 * Deserialize the [Response] to the [this] into a [T] using [U]101 *102 * @see ResultHandler103 *104 * @param deserializable [U] the instance that performs deserialization105 * @param handler [ResultHandler<T>] handler that has a [Result]106 * @return [CancellableRequest] the request that can be cancelled107 */108fun <T : Any, U : Deserializable<T>> Request.response(deserializable: U, handler: ResultHandler<T>): CancellableRequest =109 response(deserializable,110 { _, _, value -> handler(Result.Success(value)) },111 { _, _, error -> handler(Result.Failure(error)) }112 )113/**114 * Deserialize the [Response] to the [this] into a [T] using [U]115 *116 * @see ResponseHandler117 *118 * @param deserializable [U] the instance that performs deserialization119 * @param handler [ResponseHandler<T>] handler that has dedicated paths for success and failure120 * @return [CancellableRequest] the request that can be cancelled121 */122fun <T : Any, U : Deserializable<T>> Request.response(deserializable: U, handler: ResponseHandler<T>): CancellableRequest =123 response(deserializable,124 { request, response, value -> handler.success(request, response, value) },125 { request, response, error -> handler.failure(request, response, error) }126 )127/**128 * Deserialize the [Response] to the [this] into a [T] using [U]129 *130 * @see Handler131 *132 * @param deserializable [U] the instance that performs deserialization133 * @param handler [Handler<T>] handler that has dedicated paths for success and failure134 * @return [CancellableRequest] the request that can be cancelled135 */136fun <T : Any, U : Deserializable<T>> Request.response(deserializable: U, handler: Handler<T>): CancellableRequest =137 response(deserializable,138 { _, _, value -> handler.success(value) },139 { _, _, error -> handler.failure(error) }140 )141/**142 * Deserialize the [Response] to the [this] into a [T] using [U]143 *144 * @note not async, use the variations with a handler instead.145 *146 * @throws Exception if there is an internal library error, not related to Network or Deserialization147 *148 * @param deserializable [U] the instance that performs deserialization149 * @return [ResponseResultOf<T>] the response result of150 */151fun <T : Any, U : Deserializable<T>> Request.response(deserializable: U): ResponseResultOf<T> {152 // First execute the network request and catch any issues153 val rawResponse = runCatching { toTask().call() }154 .onFailure { error ->155 FuelError.wrap(error, Response.error(url)).also {156 return Triple(this, it.response, Result.error(it))157 }158 }159 .getOrThrow()160 // By this time it should have a response, but deserialization might fail161 return runCatching { Triple(this, rawResponse, Result.Success(deserializable.deserialize(rawResponse))) }162 .recover { error -> Triple(this, rawResponse, Result.Failure(FuelError.wrap(error, rawResponse))) }163 .getOrThrow()164}165/**166 * Ignore the response result167 *168 * Use this method to avoid huge memory allocation when using [com.github.kittinunf.fuel.core.requests.download]169 * to a large download and without using the result [ByteArray]170 *171 * @see [com.github.kittinunf.fuel.core.Request.response]172 *173 * @note not async, use the variations with a handler instead.174 *175 * @throws Exception if there is an internal library error, not related to Network176 */177fun Request.responseUnit(): ResponseResultOf<Unit> = response(EmptyDeserializer)178private fun <T : Any, U : Deserializable<T>> Request.response(179 deserializable: U,180 success: (Request, Response, T) -> Unit,181 failure: (Request, Response, FuelError) -> Unit182): CancellableRequest {183 val asyncRequest = RequestTaskCallbacks(184 request = this,185 onSuccess = { response ->186 // The network succeeded but deserialization might fail187 val deliverable = Result.of<T, Exception> { deserializable.deserialize(response) }188 executionOptions.callback {189 deliverable.fold(190 { success(this, response, it) },191 { failure(this, response, FuelError.wrap(it, response).also { error ->192 Fuel.trace { "[Deserializable] unfold failure: \n\r$error" } })193 }194 )195 }196 },197 onFailure = { error, response ->198 executionOptions.callback {199 failure(this, response, error.also { error ->200 Fuel.trace { "[Deserializable] callback failure: \n\r$error" }201 })202 }203 }204 )205 return CancellableRequest.enableFor(this, future = executionOptions.submit(asyncRequest))206}207/**208 * Await [T] or throws [FuelError]209 * @return [T] the [T]210 */211@Throws(FuelError::class)212suspend fun <T : Any, U : Deserializable<T>> Request.await(deserializable: U): T {213 val response = suspendable().await()214 return runCatching { deserializable.deserialize(response) }215 .onFailure { throw FuelError.wrap(it, response) }216 .getOrThrow()217}218/**219 * Await the task or throws [FuelError] in current coroutine context....

Full Screen

Full Screen

TvRemoteQTService.kt

Source:TvRemoteQTService.kt Github

copy

Full Screen

...5import android.service.quicksettings.Tile6import android.service.quicksettings.TileService7import androidx.core.content.ContextCompat8import com.github.kittinunf.fuel.core.FuelManager9import com.github.kittinunf.fuel.core.requests.CancellableRequest10import com.github.kittinunf.fuel.httpGet11import com.github.kittinunf.fuel.httpPost12import com.pointlessapps.tvremote_client.App13import com.pointlessapps.tvremote_client.R14import com.pointlessapps.tvremote_client.utils.NetworkUtils15import com.pointlessapps.tvremote_client.utils.bindService16import com.pointlessapps.tvremote_client.utils.string17import kotlinx.coroutines.*18import kotlinx.coroutines.flow.first1920class TvRemoteQTService : TileService() {2122 private val coroutineScope = CoroutineScope(Dispatchers.Main)23 private val requests = mutableListOf<CancellableRequest>()24 private var forceLoadingState = false2526 private var cachedPreferencesService: PreferencesService? = null2728 private fun getPreferenceService() = (application as? App)?.preferencesService ?: (29 cachedPreferencesService ?: PreferencesService(coroutineScope, applicationContext)30 .also { cachedPreferencesService = it }31 )3233 override fun onCreate() {34 NetworkUtils.registerNetworkChangeListener(applicationContext) { available ->35 when (available) {36 false -> setState(getString(R.string.no_internet), Tile.STATE_UNAVAILABLE)37 else -> refreshState() ...

Full Screen

Full Screen

FuelGson.kt

Source:FuelGson.kt Github

copy

Full Screen

...4import com.github.kittinunf.fuel.core.ResponseDeserializable5import com.github.kittinunf.fuel.core.ResponseHandler6import com.github.kittinunf.fuel.core.ResponseResultHandler7import com.github.kittinunf.fuel.core.extensions.jsonBody8import com.github.kittinunf.fuel.core.requests.CancellableRequest9import com.github.kittinunf.fuel.core.response10import com.google.gson.Gson11import com.google.gson.reflect.TypeToken12import java.io.Reader13/**14 * Asynchronously gets a response object of [T] wrapped in [Result] via [handler]15 *16 * @param handler [ResponseResultHandler<T>] the handler that is called upon success17 * @return [CancellableRequest] request that can be cancelled18 */19inline fun <reified T : Any> Request.responseObject(noinline handler: ResponseResultHandler<T>) =20 response(gsonDeserializer(), handler)21/**22 * Asynchronously gets a response object of [T] wrapped in [Result] via [handler] using custom [Gson] instance23 *24 * @param gson [Gson] custom Gson deserializer instance25 * @param handler [ResponseResultHandler<T>] the handler that is called upon success26 * @return [CancellableRequest] request that can be cancelled27 */28inline fun <reified T : Any> Request.responseObject(gson: Gson, noinline handler: ResponseResultHandler<T>) =29 response(gsonDeserializer(gson), handler)30/**31 * Asynchronously gets a response object of [T] or [com.github.kittinunf.fuel.core.FuelError] via [handler]32 *33 * @param handler [Handle<T>] the handler that is called upon success34 * @return [CancellableRequest] request that can be cancelled35 */36inline fun <reified T : Any> Request.responseObject(handler: ResponseHandler<T>) =37 response(gsonDeserializer(), handler)38/**39 * Asynchronously gets a response object of [T] or [com.github.kittinunf.fuel.core.FuelError] via [handler]40 * using custom [Gson] instance41 *42 * @param gson [Gson] custom Gson deserializer instance43 * @param handler [Handle<T>] the handler that is called upon success44 * @return [CancellableRequest] request that can be cancelled45 */46inline fun <reified T : Any> Request.responseObject(gson: Gson, handler: ResponseHandler<T>) =47 response(gsonDeserializer(gson), handler)48/**49 * Synchronously get a response object of [T]50 *51 * @return [Triple<Request, Response, Result<T, FuelError>>] the deserialized result52 */53inline fun <reified T : Any> Request.responseObject() =54 response(gsonDeserializer<T>())55/**56 * Synchronously get a response object of [T]57 *58 * @param gson [Gson] custom Gson deserializer instance...

Full Screen

Full Screen

Reactor.kt

Source:Reactor.kt Github

copy

Full Screen

...5import com.github.kittinunf.fuel.core.Response6import com.github.kittinunf.fuel.core.deserializers.ByteArrayDeserializer7import com.github.kittinunf.fuel.core.deserializers.EmptyDeserializer8import com.github.kittinunf.fuel.core.deserializers.StringDeserializer9import com.github.kittinunf.fuel.core.requests.CancellableRequest10import com.github.kittinunf.fuel.core.response11import com.github.kittinunf.result.Result12import reactor.core.publisher.Mono13import reactor.core.publisher.MonoSink14import java.nio.charset.Charset15private fun <T : Any> Request.monoResult(async: Request.(MonoSink<T>) -> CancellableRequest): Mono<T> =16 Mono.create<T> { sink ->17 val cancellableRequest = async(sink)18 sink.onCancel { cancellableRequest.cancel() }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)...

Full Screen

Full Screen

CancellableRequest.kt

Source:CancellableRequest.kt Github

copy

Full Screen

...11 *12 * @param wrapped [Request] the request that will be running13 * @param future [Future<Response>] the running or pending request execution that will yield a [Response]14 */15class CancellableRequest private constructor(private val wrapped: Request, private val future: Future<Response>) :16 Request by wrapped, Future<Response> by future {17 private val interruptCallback by lazy { executor.interruptCallback }18 private val executor by lazy { request.executionOptions }19 override val request: CancellableRequest = this20 override fun toString() = "Cancellable[\n\r\t$wrapped\n\r] done=$isDone cancelled=$isCancelled"21 /**22 * Cancel the request, interrupt if in progress23 */24 fun cancel() = future.cancel(true)25 /**26 * Wait for the request to be finished, error-ed, cancelled or interrupted27 * @return [Response]28 */29 fun join(): Response = runCatching { future.get() }.fold(30 onSuccess = { it -> it.also { Fuel.trace { "[CancellableRequest] joined to $it" } } },31 onFailure = { error ->32 Response.error(url).also {33 Fuel.trace { "[CancellableRequest] joined to $error" }34 if (FuelError.wrap(error).causedByInterruption) {35 interruptCallback.invoke(wrapped)36 }37 }38 }39 )40 companion object {41 val FEATURE: String = CancellableRequest::class.java.canonicalName42 fun enableFor(request: Request, future: Future<Response>): CancellableRequest {43 // Makes sure the "newest" request is stored, although it should always be the same.44 val current = getFor(request) ?: CancellableRequest(request, future)45 if (request !== current) {46 request.enabledFeatures[FEATURE] = current47 }48 return current49 }50 fun getFor(request: Request): CancellableRequest? {51 return request.enabledFeatures[FEATURE] as? CancellableRequest52 }53 }54}55/**56 * Tries to cancel the request.57 *58 * @note Not all [Request] can be cancelled, so this may fail without reason.59 * @param mayInterruptIfRunning [Boolean] if the thread executing this task should be interrupted; otherwise,60 * in-progress tasks are allowed to complete.61 * @return [Boolean] true if it was cancelled, false otherwise62 */63fun Request.tryCancel(mayInterruptIfRunning: Boolean = true): Boolean {64 val feature = request.enabledFeatures[CancellableRequest.FEATURE] as? CancellableRequest65 return feature?.cancel(mayInterruptIfRunning) ?: false66}67/**68 * Get the current cancellation state69 *70 * @note This can be used in code which may not be interrupted but has certain break points where it can be interrupted.71 * @return [Boolean] true if cancelled, false otherwise72 */73val Request.isCancelled: Boolean get() = CancellableRequest.getFor(request)?.isCancelled ?: false...

Full Screen

Full Screen

HTTP.kt

Source:HTTP.kt Github

copy

Full Screen

...5 * Created by Søren Krogh Sørensen on 2019-11-07.6 * Copyright © 2019 Vejdirektoratet. All rights reserved.7 */8package dk.vejdirektoratet.vejdirektoratetsdk.http9import com.github.kittinunf.fuel.core.requests.CancellableRequest10import com.github.kittinunf.fuel.core.requests.isCancelled11import com.github.kittinunf.fuel.httpGet12import dk.vejdirektoratet.vejdirektoratetsdk.ViewType13import dk.vejdirektoratet.vejdirektoratetsdk.EntityType14import dk.vejdirektoratet.vejdirektoratetsdk.VDBounds15import dk.vejdirektoratet.vejdirektoratetsdk.Constants16import com.github.kittinunf.result.Result as FuelResult17/**18 * A request that can be cancelled19 *20 * @property request the network request21 */22class VDRequest(private val request: CancellableRequest) {23 fun cancel() {24 request.cancel()25 }26}27internal class HTTP {28 sealed class Result {29 class Success(val data: String) : Result()30 open class Error(open val exception: Exception) : Result()31 class HttpError(override val exception: Exception, val statusCode: Int) : Error(exception)32 }33 private val baseUrlSnapshot = mapOf(34 ViewType.LIST to Constants.BASE_URL_LIST_SNAPSHOT,35 ViewType.MAP to Constants.BASE_URL_MAP_SNAPSHOT36 )...

Full Screen

Full Screen

client.kt

Source:client.kt Github

copy

Full Screen

...5import com.github.kittinunf.fuel.Fuel6import com.github.kittinunf.fuel.core.Request7import com.github.kittinunf.fuel.core.ResponseHandler8import com.github.kittinunf.fuel.core.extensions.authentication9import com.github.kittinunf.fuel.core.requests.CancellableRequest10import com.github.kittinunf.fuel.gson.jsonBody11import com.github.kittinunf.fuel.gson.responseObject12private val title = Title("Termine")13data class Title(val raw: String)14data class Content(val raw: String)15data class Page(val title: Title, val content: Content)16private fun Request.authenticate(userData: UserData) = authentication().basic(userData.username, userData.password)17fun updateEventsPage(userData: UserData, events: Events, handler: ResponseHandler<Page>): CancellableRequest {18 val raw = buildString { render(events) }19 val page = Page(title, Content(raw))20 return Fuel.post(userData.calendarUrl)21 .authenticate(userData)22 .jsonBody(page)23 .responseObject(handler)24}...

Full Screen

Full Screen

CancellableRequest

Using AI Code Generation

copy

Full Screen

1request.cancel()2request.cancel()3request.cancel()4request.cancel()5request.cancel()6request.cancel()7request.cancel()8request.cancel()9request.cancel()10request.cancel()11request.cancel()12request.cancel()13val request = Fuel.get("

Full Screen

Full Screen

CancellableRequest

Using AI Code Generation

copy

Full Screen

1 val cancellableRequest = CancellableRequest(request)2 cancellableRequest.cancel()3 val cancellableRequest = CancellableRequest(request)4 cancellableRequest.cancel()5 val cancellableRequest = CancellableRequest(request)6 cancellableRequest.cancel()7 val cancellableRequest = CancellableRequest(request)8 cancellableRequest.cancel()9This file has been truncated. [show original](github.com/kittinunf/Fuel/blo...)10 2. Call the `cancel()` method on the `CancellableRequest` object. For example: `cancellableRequest.cancel()`

Full Screen

Full Screen

CancellableRequest

Using AI Code Generation

copy

Full Screen

1 println(request)2 println(response)3 println(result)4}5request.cancel()6request.cancel()

Full Screen

Full Screen

CancellableRequest

Using AI Code Generation

copy

Full Screen

1request.cancel()2repositories {3}4dependencies {5}6 Log.d("HTTPBIN", result.toString())7}

Full Screen

Full Screen

CancellableRequest

Using AI Code Generation

copy

Full Screen

1import com.github.kittinunf.fuel.core.requests.CancellableRequest2 println("Request: $request")3 println("Response: $response")4 println("Result: $result")5}6request.cancel()7import com.github.kittinunf.fuel.core.requests.CancellableRequest8 println("Request: $request")9 println("Response: $response")10 println("Result: $result")11}12request.cancel()13import com.github.kittinunf.fuel.core.requests.CancellableRequest14 println("Request: $request")15 println("Response: $response")16 println("Result: $result")17}18request.cancel()19import com.github.kittinunf.fuel.core.requests.CancellableRequest20 println("Request: $request")21 println("Response: $response")22 println("Result: $result")23}24request.cancel()25import com.github.kittinunf.fuel.core.requests.CancellableRequest26 println("Request: $request")27 println("Response: $response")28 println("Result: $result")29}30request.cancel()31import com.github.kittinunf.fuel.core.requests.CancellableRequest32val request = Fuel.get("

Full Screen

Full Screen

CancellableRequest

Using AI Code Generation

copy

Full Screen

1fun CancellableRequest.cancel() {2 cancel()3}4fun CancellableRequest.isCancelled(): Boolean = isCancelled5fun CancellableRequest.isNotCancelled(): Boolean = !isCancelled6fun CancellableRequest.isFinished(): Boolean = isFinished7fun CancellableRequest.isNotFinished(): Boolean = !isFinished8fun CancellableRequest.isRunning(): Boolean = isRunning9fun CancellableRequest.isNotRunning(): Boolean = !isRunning10fun CancellableRequest.isNotCompleted(): Boolean = !isCompleted11fun CancellableRequest.isCompleted(): Boolean = isCompleted12fun CancellableRequest.isNotSuccessful(): Boolean = !isSuccessful13fun CancellableRequest.isSuccessful(): Boolean = isSuccessful14fun CancellableRequest.isNotFaulted(): Boolean = !isFaulted15fun CancellableRequest.isFaulted(): Boolean = isFaulted16fun CancellableRequest.isNotCancelledOrFaulted(): Boolean = !isCancelledOrFaulted17fun CancellableRequest.isCancelledOrFaulted(): Boolean = isCancelledOrFaulted18fun CancellableRequest.isNotCancelledOrCompleted(): Boolean = !isCancelledOrCompleted19fun CancellableRequest.isCancelledOrCompleted(): Boolean = isCancelledOrCompleted20fun CancellableRequest.isNotCancelledOrFaultedOrCompleted(): Boolean = !isCancelledOrFaultedOrCompleted21fun CancellableRequest.isCancelledOrFaultedOrCompleted(): Boolean = isCancelledOrFaultedOrCompleted22fun CancellableRequest.isNotCancelledOrFaultedOrCompletedOrRunning(): Boolean = !isCancelledOrFaultedOrCompletedOrRunning23fun CancellableRequest.isCancelledOrFaultedOrCompletedOrRunning(): Boolean = isCancelledOrFaultedOrCompletedOrRunning24fun CancellableRequest.isNotCancelledOrFaultedOrCompletedOrRunningOrFinished(): Boolean = !isCancelledOrFaultedOrCompletedOrRunningOrFinished25fun CancellableRequest.isCancelledOrFaultedOrCompletedOrRunningOrFinished(): Boolean = isCancelledOrFaultedOrCompletedOrRunningOrFinished26fun CancellableRequest.isNotCancelledOrFaultedOrCompletedOrRunningOrFinishedOrSuccessful(): Boolean = !isCancelledOrFaultedOrCompletedOrRunningOrFinishedOrSuccessful27fun CancellableRequest.isCancelledOrFaultedOrCompletedOrRunningOrFinishedOrSuccessful(): Boolean = isCancelledOrFaultedOrCompletedOrRunningOrFinishedOrSuccessful

Full Screen

Full Screen

CancellableRequest

Using AI Code Generation

copy

Full Screen

1 .response { result ->2 }3request.cancel()4 val (bytes, error) = result5}6 val (bytes, error) = result7}8 val (bytes, error) = result9}10 val (bytes, error) = result11}12 val (bytes, error) = result13}14 val (bytes, error) = result15}16 val (bytes, error) = result17}18 val (bytes, error) = result19}20 File.createTempFile("image", "png")21}.response { request, response, result ->22 val (data, error) = result23}24 File("/path/to/image.png")25}.response { request, response, result

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.

Run Fuel automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used methods in CancellableRequest

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful