I'm trying to implement Android Paging library
with ViewModel
and Kotlin Coroutines
I have a ViewModel
that implements CoroutineScope
. It depends on Repository
:
class MovieListViewModel(
private val movieRepository: MovieRepository
) : ViewModel(), CoroutineScope {
private val job = Job()
override val coroutineContext: CoroutineContext
get() = job + Dispatchers.IO
private lateinit var _movies: LiveData<PagedList<MovieBrief>>
val movies: LiveData<PagedList<MovieBrief>>
get() = _movies
init {
launch {
_movies = LivePagedListBuilder(movieRepository.getMovies(), DATABASE_PER_PAGE)
.setBoundaryCallback(movieRepository.movieBoundaryCallback)
.build()
}
}
}
And This is my Repository
. I inject the BoundaryCallback
with Kodein
Dependecy Injector.
class MovieRepositoryImpl(
private val movieDao: MovieDao,
boundaryCallback: MovieBoundaryCallback
) : MovieRepository {
override suspend fun getMovies(): DataSource.Factory<Int, MovieBrief> {
return movieDao.getMovies()
}
override val movieBoundaryCallback = boundaryCallback
}
Inside BoundaryCallback
class The onItemAtEndLoaded
calls the RESTAPI and then saves the data to Room database (both are suspending functions). So I have to access my ViewModel's coroutine scope. What is the best practice to achieve this?
Thanks
The Paging 3 library provides first-class Kotlin support, designed to fit recommended Android app architecture and works seamlessly with other Jetpack components. It also can handle easy or complex data operations like data loading from the network, database, or a combination of different data sources.
The Paging Library lets you load data directly from your backend using keys that the network provides. Your data can be uncountably large. Using the Paging Library, you can load data into pages until there isn't any data remaining. You can observe your data more easily.
Paging library version 3 is now available and supports Coroutine
.
PagedList.BoundaryCallback
is now Deprecated
and for this case we need to use RemoteMediator
and it has a suspend fun load
for handling Remote+Local
pagination
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With