Kotlin协程等待工作完成

时间:2020-05-16 06:53:45

标签: android performance kotlin mvvm kotlin-coroutines

我有一个ViewModel。在它的内部,我有一个函数可以从手机内部存储中获取一些图像。

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

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

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

1 个答案:

答案 0 :(得分:0)

这样做:

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
}