强制分页库数据源刷新

时间:2018-11-06 12:52:36

标签: android-architecture-components android-jetpack android-livedata android-paging android-architecture-lifecycle

在ViewModel中,我使用

加载数据
private val pagingConfig = PagedList.Config.Builder()
    .setEnablePlaceholders(false)
    .setInitialLoadSizeHint(INITIAL_LOAD_SIZE_HINT)
    .setPageSize(PAGE_SIZE)
    .build()

val notificationList = LivePagedListBuilder<Long, Notification>(dataSourceFactory, pagingConfig).build()

哪个工作正常。但是,当我的数据更改时,LiveData<PagedList<Notification>>不会得到通知。我可以做些什么来触发LiveData刷新(ViewModel知道何时发生更改)。

2 个答案:

答案 0 :(得分:1)

您可以使用invalidate()中的DataSource方法触发数据更新。

  

使用分页库时,由数据层决定在表或行过时时通知应用程序的其他层。为此,请从为应用选择的invalidate()类中调用DataSource

更多信息:Notify when data is invalid

答案 1 :(得分:0)

根据官方文档:https://developer.android.com/topic/libraries/architecture/paging/data#notify-data-invalid

您必须致电dataSourceLiveData.value?.invalidate()

我这样说:

OnRefresh:视图实现 SwipeRefreshLayout.OnRefreshListener

override fun onRefresh() {
    brewerViewModel.retry()
}

在我的视图模型中定义方法刷新:

fun refresh() {
    brewerDataSourceFactory.refresh()
}

就我而言,我正在使用改造从服务器获取数据

ItemResponse是我从服务器(Retrofit)获取的对象

class DataSourceFactory : DataSource.Factory<Int, ItemResponse>() {

    lateinit var dataSource: DataSource
    var dataSourceLiveData: MutableLiveData<DataSource> =
        MutableLiveData<DataSource>()

    override fun create(): DataSource<Int, ItemResponse> {

        dataSource = DataSource()
        dataSourceLiveData.postValue(dataSource)
        return dataSource

    }

    fun refresh() {
        dataSourceLiveData.value?.invalidate()
    }
}

在我的数据源中的定义如下:

class DataSource : PageKeyedDataSource<Int, ItemResponse>

希望对您有帮助!

相关问题