Boundary Callback (Android Paging Library) with CoroutineScope
Asked Answered
M

1

6

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

Miramontes answered 31/12, 2018 at 11:36 Comment(4)
have you found any solution to that? i am not satisfied with my current oneMylor
@NoushadHasan not till now, need to pass the scope via method/constructor injectionMiramontes
Your repository should not get the coroutine scope to do its work (since it's someone else's scope, why would it?). I think your problem arises because you are using different paradigms to fetch your data: cooroutines and callback. I recommend using suspendCoroutine (or suspendCancelableCoroutine to convert your callback provider to provide a suspend function, so you can easily use it in your view model.Squally
@AdibFaramarzi can u explain more? I didn't get itMiramontes
M
1

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

Miramontes answered 19/9, 2020 at 14:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.