# flow

Matti MK

09/07/2020, 12:02 PM
Hey! I’m new with flow and I’ve been pondering how to implement the following data flow. My use case is that I’m using TMDB API with two endpoints: one to fetch a list of genres and second to fetch a list of movies per genre. This means that if the API returns N genres I have to make N requests to fetch the list of movies. My repository returns a flow of these objects, for example Flow<List<Genre> and Flow<List<Movie>>. My question is, what would be a flow way of “combining” these two streams, so that once the genres stream emits a value (it will only emit one value, all the genres), the genres would be looped over and movies would be queried for each, then those two combined. If I were to do this without flow I’d do something like:
Copy code
fun fetchData() {
   val genresWithMovies: List<GenreWithMovies> = dataSource.queryGenres().map { genre ->
        val movies = dataSource2.queryMovies(
        genre.movies = movies
Any tips?
Also posted on #android-architecture


09/20/2020, 4:28 PM
(Ignoring the bit where 'queryGenres()' returns an object an always empty 'movies' property to be filled in vs a new object with genre + movie ) Yes this will work -- or something close. It may not perform optimally depending on the characteristics of the 2 APIs - this query each genre one by one. You mention the database returns a Flow but your function signature is List. You are missing the 'collect' part. As written the function will not compile. If you want to return a List then change the map to collectToList() or add a .toList() However that will not complete until all genere's are queried. You an return the flow directly, if your calling code can read flows - then they would get each genre (with movie list) one a time.