Fernando Pailhe
Fernando Pailhe

Reputation: 5

How Filter a Flow<List<Item> by propertis of Item Object and return a new Flow<List<Item>>

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

Upvotes: 0

Views: 1571

Answers (1)

Mario Huizinga
Mario Huizinga

Reputation: 826

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

Upvotes: 2

Related Questions