Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 525
Saman Sattari Avatar asked Dec 31 '18 11:12

Saman Sattari


People also ask

What is paging3?

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.

What is paging Library in Android?

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.


1 Answers

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

like image 108
Saman Sattari Avatar answered Sep 29 '22 22:09

Saman Sattari