如何异步观察PagedList LiveData提交结果?

时间:2019-12-20 07:14:32

标签: android kotlin android-livedata android-paging

在以下代码段中, PagedList LiveData仅观察到一次。它将下一页成功加载到recyclerView。我们知道,它在内部使用异步调用将结果提交给适配器。

问题是如何观察插入到列表中的每个新数据的PagedList LiveData?

val callback = PostListAdapter.PagerCallback()

viewModel.posts.observe(viewLifecycleOwner, Observer<PagedList<PostData>> { pagedList ->
  adapter.submitList(pagedList) // 
  adapter.updatePostList(pagedList) // I want to update this list on new data

  pagedList.addWeakCallback(null, callback) // callback working fine.
}

我还尝试了PagedList.Callback(),并且工作正常但未观察到LiveData

class PagedCallback() : PagedList.Callback() {
    override fun onChanged(position: Int, count: Int) {}

    override fun onInserted(position: Int, count: Int) {
        println("count: $count")
    }
    override fun onRemoved(position: Int, count: Int) {}
})

1 个答案:

答案 0 :(得分:0)

我找到了适用于我的方案的解决方案并与之共享。

第一次调用后,我们无法观察到PagedList LiveData,因为它异步地将结果提交给适配器,为什么实时数据不会触发。

解决方案:我从服务器获得响应后,添加了新的LiveData并在DataSource类中对其进行了更新。

ViewModel

viewModel.posts.observe(viewLifecycleOwner, Observer { pagedList ->
    adapter.submitList(pagedList)
})

// Added new LiveData to observer my list and pass it to detail screen
viewModel.postList.observe(viewLifecycleOwner, Observer {
    adapter.updatePostList(it)
})

存储库

class MyRepository(private val api: ApiService) : {
val sourceFactory = MyDataSourceFactory(api) // create MyDataSource
val postList = Transformations.switchMap( // this is new live data to observe list
       sourceFactory.sourceLiveData) { it.postList }

val data = LivePagedListBuilder(sourceFactory, PAGE_SIZE).build() 

return Result(data, postList)
}

DataSourceFactory

class MyDataSourceFactory(private val api: ApiService) : 
    DataSource.Factory<String, PostData>() {

val sourceLiveData = MutableLiveData<MyDataSource>()

override fun create(): DataSource<String, PostData> {
   val source = MyDataSource(api)
   sourceLiveData.postValue(source)
   return source
 }
}

数据源

class MyDataSource(private val api: ApiService)
    :PageKeyedDataSource<String, PostData>() {

 val postList = MutableLiveData<List<PostData>>()

 override fun loadInitial(
     params: LoadInitialParams<String>,
     callback: LoadInitialCallback<String, PostData>) {
     //Api call here
     val list = response.body()?.data
     callback.onResult( // this line submit list to PagedList asynchronously
       list,
       response.body()?.data?.before,
       response.body()?.data?.after) 

     postList.value = response.body().data // your LiveData to observe list
}

 override fun loadAfter(
     params: LoadParams<String>,
     callback: LoadCallback<String, PostData>) {
     //Api call here
     val list = response.body()?.data?
     callback.onResult( // this line submit list to PagedList asynchronously
       list,
       response.body()?.data?.before,
       response.body()?.data?.after) 

     postList.value = response.body().data // your LiveData to observe list
}