11

我想实现jetpack分页库。

一切似乎都在工作,在从 api(使用 Retrofit2 和协程)获得响应后,android 分页回调正在调用他的 onResult 接口。

但是当接收到数据时,它并没有将它的值返回给主要活动中的 livedata。

解决办法是什么 ?

视图模型

    fun getListData(): LiveData<PagedList<DataListModel>> {
        return initializedPagedListBuilder(PagingConfig.config).build()
    }


    private fun initializedPagedListBuilder(config: PagedList.Config): LivePagedListBuilder<Int, DataListModel> {

        val dataSourceFactory = object : DataSource.Factory<Int, DataListModel>() {
            override fun create(): DataSource<Int, DataListModel> {
                return ListDataPageSource()
            }
        }
        return LivePagedListBuilder<Int, DataListModel>(dataSourceFactory, config)
    }

ListDataPageSource

class ListDataPageSource : PageKeyedDataSource<Int, DataListModel>() {

    override fun loadInitial(
        params: LoadInitialParams<Int>,
        callback: LoadInitialCallback<Int, DataListModel>
    ) {
        val apiCall = RetrofitApi.getApiList("http://jsonplaceholder.typicode.com/").create(
            MoviesApi::class.java
        )

        CoroutineScope(Dispatchers.IO).launch {
            val response = apiCall.getDataList(params.requestedLoadSize, 10)
            if (response.isSuccessful && response.body() != null) {
                callback.onResult(response.body()!!, null, 1)
            }
        }
    }

    override fun loadAfter(
        params: LoadParams<Int>,
        callback: LoadCallback<Int, DataListModel>
    ) {
        val apiCall = 
          RetrofitApi.getApiList("http://jsonplaceholder.typicode.com/").create(MoviesApi::class.java)

        CoroutineScope(Dispatchers.IO).launch {
            val response = apiCall.getDataList(params.key + 10, 10)
            if (response.isSuccessful && response.body() != null) {
                callback.onResult(response.body()!!, params.key)

            }
        }
    }

    override fun loadBefore(
        params: LoadParams<Int>,
        callback: LoadCallback<Int, DataListModel>
    ) {

    }

主要活动

override fun onCreate(savedInstanceState: Bundle?) {
       super.onCreate(savedInstanceState)
       setContentView(R.layout.activity_main)
       val adapter = ListDataAdapter()
       MainRecyclerView.adapter = adapter

       val viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
       val liveData = viewModel.getListData()
       liveData.observe(this, Observer {
           adapter.submitList(it)
       })

   }

分页配置

 companion object{
        val config = PagedList.Config.Builder()
            .setPageSize(10)
            .setInitialLoadSizeHint(10)
            .setEnablePlaceholders(false)
            .build()
    }
4

0 回答 0