【问题标题】:Kotlin Coroutines wait for job to completeKotlin Coroutines 等待作业完成
【发布时间】:2020-09-02 02:14:26
【问题描述】:

我有一个 ViewModel。在其中,我有一个从手机内部存储中获取一些图像的功能。

在获取完成之前,它会在 mainactivity 中公开 livedata。如何让协程等待任务完成并暴露实时数据。

 // This is my ViewModel

 private val _image = MutableLiveData<ArrayList<File>>()
 val images: LiveData<ArrayList<File>> get() = _image

fun fetchImage(){
    val file = Path.imageDirectory  //  returns a directory where images are stored
    val files = arrayListOf<File>()
    viewModelScope.launch {
        withContext(Dispatchers.IO) {
            if (file.exists()) {
                file.walk().forEach {
                    if (it.isFile && it.path.endsWith("jpeg")) {
                        files.add(it)
                    }
                }
            }

            files.sortByDescending { it.lastModified() } // sort the files to get newest 
                                                         // ones at top of the list
        }
    }

    _image.postValue(files)
}

是否有任何其他方法可以通过任何其他方法使这段代码更快?

【问题讨论】:

  • launch 中使用_image.postValue(files) 有什么问题?你也可以使用.invokeOnCompletion { }
  • 只有在函数可挂起时才可以等待作业,即使用suspend关键字。
  • @IR42 在启动中使用 _image.postValue(files) 有什么问题?是的,它有效

标签: android performance kotlin mvvm kotlin-coroutines


【解决方案1】:

这样做:

fun fetchImage() = viewModelScope.launch {
    val file = Path.imageDirectory  //  returns a directory where images are stored
    val files = arrayListOf<File>()

    withContext(Dispatchers.IO) {
        if (file.exists()) {
            file.walk().forEach {
                if (it.isFile && it.path.endsWith("jpeg")) {
                    files.add(it)
                }
            }
        }

        files.sortByDescending { it.lastModified() } // sort the files to get newest
        // ones at top of the list
    }

    _image.value = files
}

【讨论】:

    猜你喜欢
    • 2021-10-15
    • 2019-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-17
    • 2020-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多