首页 > 解决方案 > Fragment 中的协程导致导航时 UI 不呈现

问题描述

我在片段中使用协程来处理网络请求。但是,当我导航到另一个片段时,下一个片段的 UI 是空白的,并且没有加载任何内容。我正在使用生命周期范围,所以我认为协程会在销毁时被取消/清理,但 UI 返回的唯一方法是我注释掉协程。

 lifecycleScope.launch(context = Dispatchers.IO){
        if (pdfResponse != null) {
            try {
                file = getTempPdfFile(pdfResponse)
            } catch (e: Exception) {

            }
    }
}

  private fun getTempPdfFile(body: ResponseBody): File? {
    return try {
        val file = File.createTempFile("myfile", ".pdf")
        var inputStream: InputStream? = null
        var outputStream: OutputStream? = null
        try {
            val fileReader = ByteArray(4096)
            var fileSizeDownloaded: Long = 0
            inputStream = body.byteStream()
            outputStream = FileOutputStream(file)
            while (true) {
                val read: Int = inputStream.read(fileReader)
                if (read == -1) {
                    break
                }
                outputStream.write(fileReader, 0, read)
                fileSizeDownloaded += read.toLong()
            }
            outputStream.flush()
            return file
        } catch (e: IOException) {
            null
        } finally {
            inputStream?.close()
            outputStream?.close()
        }
    } catch (e: IOException) {
        null
    }
}

谁能帮我诊断一下这个问题的原因?

标签: kotlinkotlin-coroutines

解决方案


我在视图模型中创建了一个挂起函数,如下所示:

 suspend fun createPdfFile()  =
    withContext(Dispatchers.IO) {
        if (getPdfResponse() != null) {
            try {
                file = getPdfResponse()?.let { getTempPdfFile(it) }
            } catch (e: Exception) {
            }
        }
    }

然后在视图中我使用以下方法调用它:

lifecycleScope.launch(Dispatchers.Main) {
   createPdfFile()
}

推荐阅读