...

/

flatMap and Terminal Operations

flatMap and Terminal Operations

Learn about a few more functions and see their code visualizations.

flatMap

Another well-known function for collections is flatMap. In the case of collections, it’s similar to a map, but the transformation function needs to return a collection that is then flattened. For example, if we have a list of departments, each of which has a list of employees, we can use flatMap to make a list of all employees in all departments.

Press + to interact
val allEmployees: List<Employee> = departments
.flatMap { department -> department.employees }
// If we had used map, we would have a list of lists instead
val listOfListsOfEmployee: List<List<Employee>> = departments
.map { department -> department.employees }

How should flatMap look on a flow? It seems intuitive that we might expect its transformation function to return a flow that should then be flattened. The problem is that flow elements can be spread in time. So, should the flow produced from the second element wait for the one produced from the first, or should it process them concurrently? Since there’s no clear answer, there is no flatMap function for Flow; instead, there are flatMapConcat, flatMapMerge, and flatMapLatest.

flatMapConcat function

The ...