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
suspendCancelableCoroutine
to convert your callback provider to provide a suspend function, so you can easily use it in your view model. – Squally