如何从list< pair>获得列表在Android中

发布于 2025-01-25 08:46:01 字数 1167 浏览 2 评论 0原文

在我的应用程序中,我想要组合两个延期列表,为此,我使用了kotlin flowcombine& ZIP运营商!
我在下面编写代码,但是在活动中使用时,我不知道如何获取列表!

viewModel代码:

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

活动代码:

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

我想在列表中获取每个代码并设置为适配器

写入 收集,说我选择索引,例如: it [0] < /strong>

但我想获取每个列表并将其设置为回收器适配器

我该怎么办?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

踏月而来 2025-02-01 08:46:01

如果我正确理解您的问题,您想将“对列表”转换为“对列表”。您可以为此使用unzip函数。

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

在这里,电影将是Movieflow流派的电影列表将
genResflow中成为流派列表。

但是,如果您只想要这两个列表,则可以直接在活动中收集两个流,而不是第一次zipping然后解压缩。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文