Home > Software design >  How to get list from List<Pair> in Android
How to get list from List<Pair> in Android

Time:04-30

In my application I want combine two deferent lists and for this I used kotlin flow and combine & zip operators!
I write below codes, but when used in activity I don't know how can I get lists!

ViewModel codes :

class ViewModel (private val repository: Repository) : ViewModel() {

    val moviesFlow = repository.moviesList()
    val genresFlow = repository.genresList()

    fun loadData(): Flow<List<Pair<MoviesResponse.Data, GenresList>>> =
        combine(moviesFlow, genresFlow) { movieList: Response<MoviesResponse>,
                                          genreList: Response<GenresList> ->
            val movies = movieList.body()?.data
            val genres = genreList.body()!!
            return@combine movies?.zip(genres)!!
        }
}

Activity codes :

    lifecycleScope.launchWhenCreated {
        viewModel.loadData().collect {
            
        }
    }

I want get each on lists and set into adapter!

When write it into collect, say me select index such as : it[0]

But I want get each lists and set into recycler adapter.

How can I it?

CodePudding user response:

If I understand you question correctly, you want to convert "list of pairs" to "pair of lists". You can use the unzip function for this.

viewModel.loadData().collect {
    val (movies, genres) = it.unzip()
}

Here, movies will be the list of movies from moviesFlow and genres will be the list of genres from genresFlow.

But if you only wanted these two lists separately, you could have collected the two flows in the Activity directly instead of first zipping and then unzipping.

  • Related