通过 kotlin 协程中断 HttpURLConnection

Interrupt HttpURLConnection by kotlin coroutines

我正在尝试像这样将 HttpURLConnection 与 Kotlin 协程一起使用

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

取消作业时,预计会抛出 CancellationException,但由于某种原因,在建立连接时不会发生这种情况。 有没有办法通过作业取消来中断连接尝试?

如文档所述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并为其编写您自己的可取消协程适配器,或寻找开箱即用的支持协程的库。