Android 如何从流量中重设值<;列表<;Obj>&燃气轮机;并将它们全部添加到<;列表<;Int>>;?
在ViewModel中:Android 如何从流量中重设值<;列表<;Obj>&燃气轮机;并将它们全部添加到<;列表<;Int>>;?,android,kotlin,kotlin-coroutines,android-viewmodel,android-mvvm,Android,Kotlin,Kotlin Coroutines,Android Viewmodel,Android Mvvm,在ViewModel中: val drillerCatList: List<Int> = emptyList() val shownCategoriesFlow = wordDao.getShownCategories() // which returns type Flow<List<CategoryItem>> 如何从shownCategoriesFlow:FLow中检索所有categoryNumber值,并在ViewModel中使用这些值填充dril
val drillerCatList: List<Int> = emptyList()
val shownCategoriesFlow = wordDao.getShownCategories() // which returns type Flow<List<CategoryItem>>
如何从shownCategoriesFlow:FLow中检索所有categoryNumber值,并在ViewModel中使用这些值填充drillerCatList:List?首先使drillerCatList可变,如下所示:
val drillerCatList: ArrayList<Int> = ArrayList()
首先,您的属性需要是
MutableList
或var
。通常,带有只读列表的var
更可取,因为它不太容易出错。然后在一个协同程序中调用流上的collect
collect
的行为类似于Iterable上的forEach
行为,只是当元素准备就绪时,它不会阻塞其间的线程
val drillerCatList: List<Int> = emptyList()
val shownCategoriesFlow = wordDao.getShownCategories()
init { // or you could put this in a function do do it passively instead of eagerly
viewModelScope.launch {
shownCategoriesFlow.collect { drillerCatList = it.map(CategoryItem::categoryNumber) }
}
}
shownCategoriesFlow.collect {
it.forEach{ categoryItem ->
drillerCatList.add(categoryItem.categoryNumber)
}
}
val drillerCatList: List<Int> = emptyList()
val shownCategoriesFlow = wordDao.getShownCategories()
init { // or you could put this in a function do do it passively instead of eagerly
viewModelScope.launch {
shownCategoriesFlow.collect { drillerCatList = it.map(CategoryItem::categoryNumber) }
}
}
init {
shownCategoriesFlow
.onEach { drillerCatList = it.map(CategoryItem::categoryNumber) }
.launchIn(viewModelScope)
}