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

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

RxFuel.kt

Source:RxFuel.kt Github

copy

Full Screen

...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",282 replaceWith = ReplaceWith("rxResponseStringPair(charset)"),283 level = DeprecationLevel.ERROR284)...

Full Screen

Full Screen

FileViewActivity.kt

Source:FileViewActivity.kt Github

copy

Full Screen

1package xo.william.pixeldrain2import android.os.Bundle3import android.util.Log4import android.view.MenuItem5import android.view.View6import android.widget.*7import androidx.appcompat.app.AppCompatActivity8import androidx.lifecycle.MutableLiveData9import com.bumptech.glide.Glide10import com.github.kittinunf.fuel.core.requests.CancellableRequest11import com.github.kittinunf.fuel.core.requests.tryCancel12import com.github.kittinunf.result.Result13import com.google.android.exoplayer2.MediaItem14import com.google.android.exoplayer2.SimpleExoPlayer15import com.google.android.exoplayer2.ui.PlayerView16import kotlinx.android.synthetic.main.activity_file_view.*17import kotlinx.serialization.decodeFromString18import kotlinx.serialization.json.Json19import xo.william.pixeldrain.api.FuelService20import xo.william.pixeldrain.fileList.InfoModel21class FileViewActivity : AppCompatActivity() {22 private val format = Json { ignoreUnknownKeys = true }23 private lateinit var infoModel: InfoModel;24 private lateinit var exoPlayer: SimpleExoPlayer25 private lateinit var request: CancellableRequest26 private var textLiveData = MutableLiveData<String>()27 override fun onCreate(savedInstanceState: Bundle?) {28 super.onCreate(savedInstanceState)29 setContentView(R.layout.activity_file_view)30 setSupportActionBar(sub_toolbar)31 supportActionBar?.apply {32 setDisplayHomeAsUpEnabled(true)33 }34 val infoModelString: String? = intent.getStringExtra("infoModel")35 if (infoModelString !== null) {36 infoModel = format.decodeFromString(infoModelString);37 } else {38 infoModel = InfoModel("")39 Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();40 }41 loadFile()42 }43 private fun loadFile() {44 val type = infoModel.mime_type;45 if (type.contains("image")) {46 loadImage();47 }48 if (type.contains("video") || type.contains("audio")) {49 loadVideo()50 }51 if (type.contains("text")) {52 loadText();53 }54 }55 private fun loadImage() {56 val imageFile = findViewById<ImageView>(R.id.imageFile)57 val fileProgress = findViewById<ProgressBar>(R.id.fileProgressBar);58 try {59 val urlString = infoModel.getFileUrl()60 imageFile.visibility = View.VISIBLE61 imageFile.contentDescription = infoModel.name;62 Glide.with(this).load(urlString).fitCenter().into(imageFile)63 fileProgress.visibility = View.GONE64 } catch (e: Exception) {65 fileProgress.visibility = View.GONE66 Toast.makeText(this, "Error: ${e.message}", Toast.LENGTH_LONG).show();67 }68 }69 private fun loadVideo() {70 val fileProgress = findViewById<ProgressBar>(R.id.fileProgressBar)71 fileProgress.visibility = View.GONE72 val videoExoFile = findViewById<PlayerView>(R.id.videoExoFile)73 videoExoFile.visibility = View.VISIBLE74 exoPlayer = SimpleExoPlayer.Builder(this).build()75 videoExoFile.player = exoPlayer;76 val mediaItem: MediaItem = MediaItem.fromUri(infoModel.getFileUrl())77 exoPlayer.setMediaItem(mediaItem);78 exoPlayer.prepare()79 exoPlayer.play()80 }81 private fun loadText() {82 request = FuelService().getFileText(infoModel.getFileUrl())83 .responseString() { _, _, result ->84 when (result) {85 is Result.Success -> {86 textLiveData.postValue(result.get())87 }88 is Result.Failure -> {89 textLiveData.postValue(result.error.exception.message)90 }91 }92 }93 textLiveData.observe(this, {94 val fileProgress = findViewById<ProgressBar>(R.id.fileProgressBar)95 val textFile = findViewById<TextView>(R.id.textFile)96 val textScrollView = findViewById<ScrollView>(R.id.textScrollView)97 fileProgress.visibility = View.GONE98 textFile.text = it99 textFile.visibility = View.VISIBLE100 textScrollView.visibility = View.VISIBLE101 })102 }103 override fun onBackPressed() {104 if (this::exoPlayer.isInitialized) {105 exoPlayer.release();106 }107 if (this::request.isInitialized) {108 request.tryCancel()109 }110 super.onBackPressed()111 }112 override fun onOptionsItemSelected(item: MenuItem): Boolean {113 if (this::exoPlayer.isInitialized) {114 exoPlayer.release();115 }116 if (this::request.isInitialized) {117 request.tryCancel()118 }119 finish();120 return super.onOptionsItemSelected(item)121 }122}...

Full Screen

Full Screen

TvRemoteQTService.kt

Source:TvRemoteQTService.kt Github

copy

Full Screen

...4546 runCatching {47 forceLoadingState = true48 setState(getString(R.string.loading), Tile.STATE_UNAVAILABLE)49 requests.all { it.cancel() }50 requests.add("/power".httpPost().string {51 forceLoadingState = false52 this@TvRemoteQTService.setState(it)53 when (it) {54 "true", "on" -> openConnection()55 "false", "off" -> closeConnection()56 }57 })58 }59 }60 }6162 private suspend fun loadDevice(): Boolean {63 val deviceUri = getPreferenceService().getSettings().first().deviceInfo?.uri ...

Full Screen

Full Screen

Reactor.kt

Source:Reactor.kt Github

copy

Full Screen

...13import 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)30 }31 }32/**...

Full Screen

Full Screen

CancellableRequest.kt

Source:CancellableRequest.kt Github

copy

Full Screen

...4import com.github.kittinunf.fuel.core.Request5import com.github.kittinunf.fuel.core.Response6import java.util.concurrent.Future7/**8 * Request extension that adds [cancel] to a Running or Pending [Request].9 *10 * @see [com.github.kittinunf.fuel.core.Deserializable] used when using handlers11 *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

...14import 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 )37 private val baseUrlEntity = mapOf(38 ViewType.LIST to Constants.BASE_URL_LIST_SNAPSHOT,39 ViewType.MAP to Constants.BASE_URL_MAP_SNAPSHOT40 )41 internal fun request(tag: String?, entityTypes: List<EntityType>, region: VDBounds?, zoom: Int?, viewType: ViewType, apiKey: String, onCompletion: (result: Result) -> Unit): VDRequest {42 val url = buildUrl(tag, entityTypes, region, zoom, viewType, apiKey)43 return request(url, onCompletion)44 }45 private fun request(url: String, onCompletion: (result: Result) -> Unit): VDRequest {46 val httpRequest = url.httpGet()47 .interrupt { request -> println("${request.url} was interrupted and cancelled") }48 .response { request, response, result ->49 if (!request.isCancelled) {50 when (result) {51 is FuelResult.Failure -> {52 onCompletion(Result.HttpError(result.error, response.statusCode))53 }54 is FuelResult.Success -> {55 onCompletion(Result.Success(String(result.value)))56 }57 }58 }59 }60 return VDRequest(httpRequest)61 }...

Full Screen

Full Screen

StrecklistanPoller.kt

Source:StrecklistanPoller.kt Github

copy

Full Screen

...17 private var pollDelayJob: Job? = null18 private var pollRequest: CancellableRequest? = null19 private var pollStartedAt: Instant = Instant.now()20 private var sessionId: Long = 021 private var canceled = false22 fun stopPolling() {23 canceled = true24 pollDelayJob?.cancel()25 pollDelayJob = null26 pollRequest?.cancel()27 pollRequest = null28 }29 fun startPolling() {30 if (this.canceled) {31 this.canceled = false32 sendPollRequest()33 }34 }35 private fun sendPollRequest() {36 if (canceled) {37 return38 }39 this.sessionId += 140 pollStartedAt = Instant.now()41 val requestId = sessionId42 pollRequest =43 connection.pollTransaction(10000) { result: Result<TransactionPollResponse, FuelError> ->44 runOnUiThread {45 if (requestId == sessionId && !canceled) {46 pollRequest = null47 result.fold(48 success = {49 handlePollResponse(it)50 },51 failure = {52 error_callback(it)53 }54 )55 }56 }57 }58 }59 private fun handlePollResponse(response: TransactionPollResponse) {...

Full Screen

Full Screen

FuelCancellable.kt

Source:FuelCancellable.kt Github

copy

Full Screen

...3import org.tiramisu.http.HttpCancellable4class FuelCancellable(5 private val request: CancellableRequest6) : HttpCancellable {7 override fun cancel() {8 request.cancel()9 }10}...

Full Screen

Full Screen

cancel

Using AI Code Generation

copy

Full Screen

1}2request.cancel()3public void success(Request request, Response response, String s) {4}5public void failure(Request request, Response response, FuelError fuelError) {6}7});8request.cancel();

Full Screen

Full Screen

cancel

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()

Full Screen

Full Screen

cancel

Using AI Code Generation

copy

Full Screen

1result.fold({ data ->2println(data)3}, { err ->4println(err)5})6}7request.cancel()8request.cancel(CancellationException("I don't want this anymore"))9request.cancel(CancellationException("I don't want this anymore"), true)10result.fold({ data ->11println(data)12}, { err ->13println(err)14})15}16FuelManager.instance.cancelAll()17FuelManager.instance.cancelAll(CancellationException("I don't want this anymore"))18FuelManager.instance.cancelAll(CancellationException("I don't want this anymore"), true)19result.fold({ data ->20println(data)21}, { err ->22println(err)23})24}25result.fold({ data ->26println(data)27}, { err ->28println(err)29})30}31result.fold({ data ->32println(data)33}, { err ->

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 method 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