android - Kotlin Coroutines 等待作业完成
问题描述
我有一个视图模型。在其中,我有一个从手机内部存储中获取一些图像的功能。
在获取完成之前,它会在 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)
}
有没有其他方法可以通过任何其他方法使这段代码更快?
解决方案
像这样做:
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
}
推荐阅读
- assembly - x86 程序集 - 编码相对 jmp
- python - 这是访问私有变量吗?
- c# - PythonNet:嵌入c#时如何从python函数通知c#调用者
- java - 将对列表与 Java 中的自定义类的元素进行比较
- answer-set-programming - Clingo:按顺序(索引)比较字符串文字?
- javascript - JavaScript 中回调函数的替代方案
- c# - 如果我们使用表达式交互 ChangepropertyAction,XAML 中的两种方式绑定不会更新源
- operating-system - MBR 十六进制转储的用途是什么,使用它可以做什么?
- c# - 如何使用 Sinc 函数将图像大小加倍是 asp.net c#?
- reactjs - 如何将渲染函数之外的数组映射到setState?