如何用kotlin流实施分页

发布于 2025-01-30 17:22:01 字数 2525 浏览 5 评论 0原文

我是Kotlin Flow的新手。我正在关注 this 在Android中设置UI层。

这是我的UI状态流,

private val _teamsUiState = MutableStateFlow(TeamsUiState())
val teamsUiState: StateFlow<TeamsUiState> = _teamsUiState.asStateFlow()

这是我的TeamSuistate数据类别:

data class TeamsUiState(
    val teamItems: ArrayList<Team> = ArrayList(),
    val error: String? = null
)

我正在向API中的API响应,并像这样处理它,

fetchTeamsJob = viewModelScope.launch {
            fetchTeamsJob?.cancel()
            response.collectLatest {
                when (it) {
                    is Result.Success -> {
                        it.data?.payload?.let { payload ->
                            if (payload.teams != null) {
                                _teamsUiState.update { teamsState ->
                                    // Problem here
                                    teamsState.copy(teamItems = ArrayList(payload.teams))
                                }
                            }
                            val totalCount = payload.total_count?.toInt() ?: 0
                            val listSize = teamsUiState.value.teamItems.size
                            teamsNextPageAvailable = (listSize >= totalCount).not()
                        }
                    }
                    is Result.Loading -> {
                        toggleTeamProgress(isRefresh)
                    }
                    is Result.Error -> {
                        _showToast.emit(
                            it.exception.message ?: getApplication<Application>().getString(
                                R.string.something_wrong_try_again
                            )
                        )
                        toggleTeamProgress(isRefresh)
                    }
                }
            }

并且在片段中,我会这样观察到这样的片段:

viewLifecycleOwner.lifecycleScope.launch {
    viewLifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
        teamsAdapter.submitList(it.teamItems)            
    }
}

由于我有分页,我需要附加团队。列表到已经存在的列表。

我唯一可以做到的方法是做这样的事情:

_teamsUiState.update { teamsState ->
    val temp = ArrayList(teamsState.teamItems)
    temp.addAll(payload.teams)
    teamsState.copy(teamItems = temp)
}

有没有更好的方法来实现我想要的东西而不使用temp变量?

I am new to kotlin flows. I am following this to set up the UI layer in Android.

This is my UI stateFlow

private val _teamsUiState = MutableStateFlow(TeamsUiState())
val teamsUiState: StateFlow<TeamsUiState> = _teamsUiState.asStateFlow()

This is my TeamsUiState data class:

data class TeamsUiState(
    val teamItems: ArrayList<Team> = ArrayList(),
    val error: String? = null
)

I am fetching the response from the API on a coroutine and handling it like this

fetchTeamsJob = viewModelScope.launch {
            fetchTeamsJob?.cancel()
            response.collectLatest {
                when (it) {
                    is Result.Success -> {
                        it.data?.payload?.let { payload ->
                            if (payload.teams != null) {
                                _teamsUiState.update { teamsState ->
                                    // Problem here
                                    teamsState.copy(teamItems = ArrayList(payload.teams))
                                }
                            }
                            val totalCount = payload.total_count?.toInt() ?: 0
                            val listSize = teamsUiState.value.teamItems.size
                            teamsNextPageAvailable = (listSize >= totalCount).not()
                        }
                    }
                    is Result.Loading -> {
                        toggleTeamProgress(isRefresh)
                    }
                    is Result.Error -> {
                        _showToast.emit(
                            it.exception.message ?: getApplication<Application>().getString(
                                R.string.something_wrong_try_again
                            )
                        )
                        toggleTeamProgress(isRefresh)
                    }
                }
            }

And in the fragment I am observing it like this:

viewLifecycleOwner.lifecycleScope.launch {
    viewLifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
        teamsAdapter.submitList(it.teamItems)            
    }
}

Since I have pagination, I need to append the teams list to the already existing list.

The only way i could do this is by doing something like this:

_teamsUiState.update { teamsState ->
    val temp = ArrayList(teamsState.teamItems)
    temp.addAll(payload.teams)
    teamsState.copy(teamItems = temp)
}

Is there a better way to achieve what I want without using a temp variable?

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

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

发布评论

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

评论(2

森林很绿却致人迷途 2025-02-06 17:22:01

我想有很多方法可以完成这种理想的行为,但是很多锅炉板也会随附,我认为这里最好的方法是实施分页3,以便您可以以一种非常简单,有效的方式处理分页。来源:

如果您对我使用此库进行的编码任务项目有疑问,您可以随时查看:

I guess there will be many ways to get this desired behaviour done, but a lot of boiler plate will come with as well, I think the best approach here would be to implement Paging 3 so you can handle pagination in a very easy and efficient way. Sources:

You can always have a look if you have doubts at a coding task project I made with this library:

绻影浮沉 2025-02-06 17:22:01

您可以在_teamSuistate上使用getAndupDate {}

_teamsUiState.getAndUpdate { existingItems ->
    val newList = existingItems.teamItems.plus(newItems)
    TeamUiState(newList)
}

You could use getAndUpdate {} on _teamsUiState.

_teamsUiState.getAndUpdate { existingItems ->
    val newList = existingItems.teamItems.plus(newItems)
    TeamUiState(newList)
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文