如何从 Flow<List<Obj>> 中检索值并将它们全部添加到 <List<Int>>?

How to retieve values from Flow<List<Obj>> and add all of them to <List<Int>>?

在视图模型中:

val drillerCatList: List<Int> = emptyList()

val shownCategoriesFlow = wordDao.getShownCategories() // which returns type Flow<List<CategoryItem>>

类别对象:

data class CategoryItem(
    val categoryName: String,
    val categoryNumber: Int,
    val categoryShown: Boolean = false,
    @PrimaryKey(autoGenerate = true) var id: Int = 0
) : Parcelable {
}

如何从 shownCategoriesFlow: FLow 中检索所有 categoryNumber 值并在 ViewModel 中使用这些值填充 drillerCatList: List?

首先使 drillerCatList 可变,如下所示:

val drillerCatList: ArrayList<Int> = ArrayList()

现在从shownCategoriesFlow收集列表:

shownCategoriesFlow.collect {
   it.forEach{ categoryItem ->
        drillerCatList.add(categoryItem.categoryNumber)
   }
}

首先,您的 属性 需要是 MutableListvar。通常,带有只读 Listvar 更可取,因为它不易出错。然后你在协程中调用 Flow 上的 collectcollect 的行为有点像 forEach 对 Iterable 的行为,只是它不会在元素准备好时阻塞中间的线程。

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