Kotlin return 当异步进程结束时

Kotlin return when asynchronous progress ends

我正在尝试从下载文件的函数中 return 一个布尔值。 但是在进度处理程序中,我无法 return 将“true”语句返回给函数。

我找到了一些文章来附加一个接口来返回通信,但不幸的是我不能让它为这个 okhttpd 功能工作。

还有其他选择吗?这是我正在使用的代码。

private fun downloadFile(url: String,key: String):Boolean {
    
        val formBody: RequestBody = FormBody.Builder()
            .add("key", key)
            .build()

        val downloadClient = OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(180, TimeUnit.SECONDS).readTimeout(180, TimeUnit.SECONDS)
            .build()

        val request: Request = Request.Builder()
            .url(url)
            .post(formBody)
            .addHeader("typeAttach", "download")
            .build()
    

        downloadClient.newCall(request).enqueue(object : Callback {

            override fun onFailure(call: Call, e: IOException) {
                Log.e("failure Response", e.toString())
                call.cancel()
            }

            override fun onResponse(call: Call, response: Response) {
                val tmpDl = File(globalPath, Utility.tmpDir + "/test.zip")
                val sourceBytes = response.body!!.source()
                val sourceSize = response.body!!.contentLength()
                val sink: BufferedSink = tmpDl.sink().buffer()

                var totalRead: Long = 0
                var lastRead: Long

                while (sourceBytes
                        .read(sink.buffer, 8L * 1024)
                        .also { lastRead = it } != -1L
                ) {
                    totalRead += lastRead
                    sink.emitCompleteSegments()

                    Log.d("progress”, totalRead + "/" + sourceSize)

                }
                //return true when its finished

                sink.writeAll(response.body!!.source())
                sink.close()
            }


        })

 return false
    
}

使用回调尝试下一个方法:

private fun downloadFile(
  url: String,
  key: String, 
  downloadCompleteCallback: () -> Unit
) { 
 // your code
}

并在 while 循环中通知下载完成:

while (sourceBytes.read(sink.buffer, 8L * 1024).also { 
    lastRead = it } != -1L) 
{
  totalRead += lastRead
  sink.emitCompleteSegments()

  if (totalRead == 100) {
    downloadCompleteCallback.invoke()
  }                  
}