androidkotlinkotlinx.coroutinesandroid-viewmodelandroid-paging

Boundary Callback (Android Paging Library) with CoroutineScope


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


Solution

  • 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