Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/215.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何从流量中重设值<;列表<;Obj>&燃气轮机;并将它们全部添加到<;列表<;Int>>;?_Android_Kotlin_Kotlin Coroutines_Android Viewmodel_Android Mvvm - Fatal编程技术网

Android 如何从流量中重设值<;列表<;Obj>&燃气轮机;并将它们全部添加到<;列表<;Int>>;?

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

在ViewModel中:

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