Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading