提问人:Stevie 提问时间:11/16/2023 最后编辑:Stevie 更新时间:11/16/2023 访问量:50
如何在 Jetpack pose 中从 Flow<PagingData<>> 中删除/更新项目?
How to remove/update an item from Flow<PagingData<>> in Jetpack compose?
问:
祝你有美好的一天。 我是 jetpack compose 的新手,目前不知道如何更新 Flow Paging 数据中的项目。我知道我可以将项目更新到服务器并调用以再次获取所有这些项目,但这不是一个好方法。我认为我们仍然有更好的方法来做到这一点(希望它是对的)。 这是我正在做的
override fun items(): Flow<PagingData<Item>> {
return Pager(
config = PagingConfig(
pageSize = ITEM_PER_PAGE,
),
pagingSourceFactory = {
ItemPagingSource(api)
}
).flow
}
在 ViewModel 中:
val items = conversationRepository.items().cachedIn(viewModelScope)
编辑1:
- 我只需从 UI 更新即可进行更新,但列表中的对象仍保留以前的值。
- 关于删除项目,我尝试将项目添加到列表中并像这样过滤,但列表没有重置,因此效果不佳:/
var items: Flow<PagingData<EndedConversation>> = conversationRepository.items()
.map {
it.filter {
!deletedRecentIds.contains(it.id)
}
}
.cachedIn(viewModelScope)
答:
0赞
Jan Bína
11/16/2023
#1
您可以使用 PagingData.map(
) 和 PagingData.filter()
映射/过滤分页数据:
private val allItems = conversationRepository.items().cachedIn(viewModelScope)
private val removedItems = MutableStateFlow(setOf(1L))
private val updatedItems = MutableStateFlow(mapOf(2L to Item(id = 2L, title = "Updated")))
val items = combine(allItems, removedItems, updatedItems) { all, removed, updated ->
all.filter { it.id !in removed }
.map { updated.getOrDefault(key = it.id, defaultValue = it) }
}
fun removeItem(item: Item) {
removedItems.update { it + item.id }
}
fun updateItem(item: Item) {
updatedItems.update { it + (item.id to item) }
}
评论
0赞
Stevie
12/7/2023
它工作得很好,谢谢
评论