How to remove/update an item from Flow<PagingData<>> in Jetpack compose?

640 views Asked by At

Have a nice day guys. I am new to jetpack compose and currently don't know how to update an Item in a Flow Paging data. I know that I can update the Item to server and call to get all of them again but it is not a good way. I think we still have a better way to do it (hoping that it's right). Here is what I am doing

  override fun items(): Flow<PagingData<Item>> {
    return Pager(
      config = PagingConfig(
        pageSize = ITEM_PER_PAGE,
      ),
      pagingSourceFactory = {
        ItemPagingSource(api)
      }
    ).flow
  }

In ViewModel:

  val items = conversationRepository.items().cachedIn(viewModelScope)

Edit 1:

  • I am able to update by just updating from UI, but the object in the list still remains the previous value.
  • About deleting an item, I try by adding an item to a list and filter like this, but the list is not reset so it is not works at well :/
  var items: Flow<PagingData<EndedConversation>> = conversationRepository.items()
    .map {
      it.filter {
        !deletedRecentIds.contains(it.id)
      }
    }
    .cachedIn(viewModelScope)
1

There are 1 answers

1
Jan Bína On BEST ANSWER

You can map/filter your paging data using PagingData.map() and 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) }
}