【问题标题】:How to retieve values from Flow<List<Obj>> and add all of them to <List<Int>>?如何从 Flow<List<Obj>> 中检索值并将它们全部添加到 <List<Int>>?
【发布时间】:2021-07-03 05:36:36
【问题描述】:

在 ViewModel 中:

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?

【问题讨论】:

    标签: android kotlin kotlin-coroutines android-viewmodel android-mvvm


    【解决方案1】:

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

    val drillerCatList: ArrayList<Int> = ArrayList()
    

    现在从shownCategoriesFlow收集列表:

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

    【讨论】:

      【解决方案2】:

      首先,您的资源必须是MutableListvar。通常,var 和只读的List 更可取,因为它不易出错。然后你在协程中调用你的 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)
      }
      

      【讨论】:

        猜你喜欢
        • 2021-06-26
        • 2022-01-02
        • 1970-01-01
        • 1970-01-01
        • 2022-12-17
        • 1970-01-01
        • 1970-01-01
        • 2021-12-29
        • 1970-01-01
        相关资源
        最近更新 更多