Home > Software engineering >  How Filter a Flow<List<Item> by propertis of Item Object and return a new Flow<List<I
How Filter a Flow<List<Item> by propertis of Item Object and return a new Flow<List<I

Time:04-05

I am new to kotlin and reactive programming. I have a repository that runs a query to a room database. I want to filter the list of Items according to some parameters before sending it to the viewmodel.

I don't know what I'm doing wrong, but I think it has to do with not understanding something about Flow. It gives me an error that I return a unit and not a list.

 suspend fun getFilterList(flowList: Flow<List<Item>>): Flow<List<Item>>{

    val filterList: MutableList<Item> = mutableListOf()
    flowList.collectLatest { list ->
        list.toList().forEach { item ->
            if (item.owner1 != 100){
                filterList.add(item)
            }
        }

    }

    return filterList.asFlow()
}

CodePudding user response:

A function that returns a flow does not need to suspend. I assume this should meet your requirements:

@OptIn(ExperimentalCoroutinesApi::class)
fun getFilterList(flowList: Flow<List<Item>>): Flow<List<Item>>{
    return flowList.mapLatest { list ->
        list.filter { it.owner1 != 100 }
    }
}
  • Related