I wanna to implement jetpack paging library.
everything seems working, after getting response from api (using Retrofit2 and coroutine) android paging callback is calling his onResult interface.
but it's not returning it's value to livedata in main activity when data received.
What is the solution ?
ViewModel
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>
) {
}
MainActivity
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)
})
}
PagingConfig
companion object{
val config = PagedList.Config.Builder()
.setPageSize(10)
.setInitialLoadSizeHint(10)
.setEnablePlaceholders(false)
.build()
}