I want to implement my custom PagedList.BoundaryCallback with coroutines, liveData and repository pattern using Paging Library 2, but I couldn't find a good example of integration of these libraries.
Even in Android official samples, they use enqueue and callbacks to perform the API request with paging 2...
I read this Medium post also but it use a coroutines scope inside the boundary callback and I think that is not a good practice.
Is there any way to achieve it? Or should I migrate to Paging 3?
This solution works for me:
I injected a CoroutinesDispatcherProvider in my Repository:
class MyRepository @Inject constructor(
private val remoteDataSource: MyRemoteDataSource,
private val localDataSource: MyDao,
private val coroutinesDispatcherProvider: CoroutinesDispatcherProvider
) {...}
Then inside my repository, I passed this provider to my boundary callback:
private val boundaryCallback =
MyBoundaryCallback(remoteDataSource, localDataSource, coroutinesDispatcherProvider)
fun getList(): LiveData<PagedList<MyModel>> = LivePagedListBuilder(
localDataSource.getAll(),
pagedListConfig
).setBoundaryCallback(boundaryCallback).build()
And finally, I use this dispatcher in my boundary implementation to launch my request from repository:
private val ioCoroutineScope by lazy {
CoroutineScope(coroutinesDispatcherProvider.io)
}
override fun onZeroItemsLoaded() {
ioCoroutineScope.launch {
remoteDataSource.getList()
}
}