Update list items in PagingLibrary w/o using Room (Network only)

前端 未结 2 1759
闹比i
闹比i 2020-12-14 12:27

I\'m using Paging Library to load data from network using ItemKeyedDataSource. After fetching items user can edit them, this updates are done i

相关标签:
2条回答
  • 2020-12-14 12:55

    All you need to do is to invalidate current DataSource each time you update your data.

    What I would do:

    • move networking logic from MentionKeyedDataSource to new class that extends PagedList.BoundaryCallback and set it when building your PagedList.

    • move all you data to some DataProvider that holds all your downloaded data and has reference to DataSource. Each time data is updated in DataProvider invalidate current DataSource

    Something like that maybe

        val dataProvider = PagedDataProvider()
        val dataSourceFactory = InMemoryDataSourceFactory(dataProvider = dataProvider)
    

    where

    class PagedDataProvider : DataProvider<Int, DataRow> {
    
        private val dataCache = mutableMapOf<Int, List<DataRow>>()
        override val sourceLiveData = MutableLiveData<DataSource<Int, DataRow>>()
    
        //implement data add/remove/update here
        //and after each modification call
        //sourceLiveData.value?.invalidate()
    }
    

    and

    class InMemoryDataSourceFactory<Key, Value>(
        private val dataProvider: DataProvider<Key, Value>
    ) : DataSource.Factory<Key, Value>() {
    
        override fun create(): DataSource<Key, Value> {
            val source = InMemoryDataSource(dataProvider = dataProvider)
            dataProvider.sourceLiveData.postValue(source)
            return source
        }
    }
    

    This approach is very similar to what Room does - every time table row is updated - current DataSource is invalidated and DataSourceFactory creates new data source.

    0 讨论(0)
  • 2020-12-14 12:55

    You can modify directly in your adapter if you called currentList like that

    class ItemsAdapter(): PagedListAdapter<Item, ItemsAdapter.ViewHolder(ITEMS_COMPARATOR) {
        ...
        fun changeItem(position: Int,newData:String) {
            currentList?.get(position)?.data = newData
            notifyItemChanged(position)
        }
       
    }
    
    0 讨论(0)
提交回复
热议问题