Search code examples
androidkotlinkotlin-coroutinesandroid-viewmodelandroid-mvvm

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


In ViewModel:

val drillerCatList: List<Int> = emptyList()

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

Catigory object:

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

How can I retrieve all categoryNumber values from shownCategoriesFlow: FLow<List> and fill drillerCatList: List with these values in ViewModel?


Solution

  • First make drillerCatList mutable as shown below:

    val drillerCatList: ArrayList<Int> = ArrayList()
    

    Now collect the list from the shownCategoriesFlow:

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