yaugenka
yaugenka

Reputation: 2871

Interrupt HttpURLConnection by kotlin coroutines

I'm trying to use HttpURLConnection with Kotlin coroutines like this

var downloadJob: Job? = null

fun triggerDownload() { 
    job = downloadFile()
}

override fun onBackPressed() {
    downloadJob.cancel()
    super.onBackPressed()
}

fun downloadFile() = launch {
    withContext(Dispatchers.IO) {
        var connnection: HttpURLConnection? = null
        try {
            connnection = url.openConnection() as HttpURLConnection
            connnection.connect()
            //do the work
        } catch (e: Exception) {
            //handle exception
        } finally {
            connnection?.disconnect()
        }
    }
}

When the job is cancelled, a CancellationException is expected to be thrown, but to some reason this does not happen while connection is being established. Is there a way to interrupt the connection attempt by job cancellation?

Upvotes: 0

Views: 1088

Answers (1)

esentsov
esentsov

Reputation: 6522

As the documentation states cancellation is cooperative. It means that it's responsibility of the coroutine code to check for cancellation and throw the exception. All suspending functions from the coroutine library are cancellable (i.e. they check for cancellation), so normally it works automatically. Obviously this is not the case with HttpURLConnection - it does not know anything about coroutines and obviously does not check for cancellation. Moreover as far as I know, this call is not cancellable at all. You might want to consider using a library like okhttp and write your own cancellable coroutine adapter for it or look for a library that supports coroutines out of the box.

Upvotes: 1

Related Questions