---
# System prepended metadata

title: 解决：Paging3 PagingDataAdapter 删除 item
tags: [開發疑難雜症, Android]

---

## 解决：Paging3 PagingDataAdapter 删除 item

ViewModel
```
    private val _removeItemFlow = MutableStateFlow(mutableListOf<Data>())
    private val removeItemFlow: Flow<MutableList<Data>> get() = _removeItemFlow
    private lateinit var pagingDataFlow: Flow<PagingData<Data>>
    
    fun getPosts(context: Context): Flow<PagingData<Data>> {
        pagingDataFlow = postRepository.getPosts(context, 10, errorHandlerDelegate)
            .cachedIn(viewModelScope)
        return pagingDataFlow
    }
    
    fun bindPaging(adapter: ItemAdapter) {
        viewModelScope.launch {
            pagingDataFlow.cachedIn(viewModelScope).combine(removeItemFlow) { pagingData, remove ->
                pagingData.filter { it !in remove }
            }.collectLatest {
                adapter.submitData(it)
            }
        }
    }

    fun remove(item: Data) {
        val removes = _removeItemFlow.value
        val list = mutableListOf(item)
        list.addAll(removes)
        _removeItemFlow.value = list
    }
```

View
```
    private fun delete(id: String) {
        launchWithViewLifecycle {
            viewModel.delete(id).collect {
                val item = itemAdapter.snapshot().find { it2 -> it2?.id == id }
                if (item != null) {
                    viewModel.remove(item)
                    viewModel.bindPaging(itemAdapter)
                    checkEmpty()
                }
            }
        }
    }
```