Best Fuel code snippet using com.github.kittinunf.fuel.core.requests.CancellableRequest.Request.tryCancel
FileViewActivity.kt
Source:FileViewActivity.kt  
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}...CancellableRequest.kt
Source:CancellableRequest.kt  
1package com.github.kittinunf.fuel.core.requests2import com.github.kittinunf.fuel.Fuel3import com.github.kittinunf.fuel.core.FuelError4import 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...Request.tryCancel
Using AI Code Generation
1when (result) {2is Result.Success -> {3println("success")4}5is Result.Failure -> {6println("failure")7}8}9}10request.tryCancel()11when (result) {12is Result.Success -> {13println("success")14}15is Result.Failure -> {16println("failure")17}18}19}20request.cancel()21when (result) {22is Result.Success -> {23println("success")24}25is Result.Failure -> {26println("failure")27}28}29}30request.cancel()31when (result) {32is Result.Success -> {33println("success")34}35is Result.Failure -> {36println("failure")37}38}39}40request.cancel()41when (result) {42is Result.Success -> {43println("success")44}45is Result.Failure -> {46println("failure")47}48}49}50request.cancel()51when (result) {52is Result.Success -> {53println("success")54}55is Result.Failure -> {56println("failure")57}58}59}60request.cancel()61when (result) {62is Result.Success -> {63println("Request.tryCancel
Using AI Code Generation
1request.response { request, response, result ->2println("request cancelled: ${request.isCancelled}")3println("response: $response")4println("result: $result")5}6request.tryCancel()7result: Failure(java.net.SocketException: Socket closed)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!!
