【问题标题】:Save file in background by Kotlin coroutines通过 Kotlin 协程在后台保存文件
【发布时间】:2020-01-30 17:06:05
【问题描述】:

在我的 Android 应用中的 ViewModel

 private fun finishProcessRecognizedCheck(
        firebaseVisionImage: FirebaseVisionImage,
        firebaseVisionText: FirebaseVisionText, recognizedCheck: Check
    ) {
        val file_prefix = resultRecognizedCheckList.size.toString()
        RecognizedCheckDataService.saveRecognizedImage(firebaseVisionImage, file_prefix)
        RecognizedCheckDataService.saveRecognizedText(firebaseVisionText, file_prefix)
       }

如您所见,我将图像文件保存到 UI 线程 的内部文件夹中。 结果应用程序被冻结。 是否可以通过 Kotlin 的协程将图像保存在 背景 上? AA

【问题讨论】:

    标签: android kotlin-coroutines


    【解决方案1】:

    协程需要一个作用域来运行。因此,我们使用调度程序和作业创建范围。

    1. 使用您创建的作业和调度程序定义作业并创建范围,如下所示:

      //Initialization of job
      private var job = Job()
      
      // Initialization of scope for the coroutine to run in
      private var scopeForSaving = CoroutineScope(job + Dispatchers.Main)
      
    2. 现在我们在单击按钮时触发保存操作,如下所示:

      private fun saveButtonClick() {
              scopeForSaving.launch { saveToStorage() }
      }
      private suspend fun saveToStorage(){
              withContext(Dispatchers.IO){
                    //Logic for saving the image goes here
              }
      }
      
    3. 我们可以取消onDestroy()中的job,这样当activity被销毁时,我们就可以确定所有的协程都被终止了。

      override fun onDestroy() {
          super.onDestroy()
          scopeForSaving.cancel()
      }
      

    【讨论】:

      猜你喜欢
      • 2017-11-26
      • 1970-01-01
      • 2015-05-23
      • 1970-01-01
      • 2023-01-22
      • 1970-01-01
      • 2016-06-10
      • 2019-02-14
      • 2020-04-12
      相关资源
      最近更新 更多