具有CoroutineScope的边界回调(Android分页库)

时间:2018-12-31 11:36:45

标签: android kotlin kotlinx.coroutines android-viewmodel android-paging

我正在尝试使用Android Paging libraryViewModel来实现Kotlin Coroutines

我有一个实现ViewModel的{​​{1}}。它取决于CoroutineScope

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() } } } 。我用Repository Dependecy注入器注入了BoundaryCallback

Kodein

内部class MovieRepositoryImpl( private val movieDao: MovieDao, boundaryCallback: MovieBoundaryCallback ) : MovieRepository { override suspend fun getMovies(): DataSource.Factory<Int, MovieBrief> { return movieDao.getMovies() } override val movieBoundaryCallback = boundaryCallback } BoundaryCallback调用RESTAPI,然后将数据保存到Room数据库中(这两个都是挂起函数)。因此,我必须访问ViewModel的协程范围。实现此目的的最佳做法是什么?

谢谢

1 个答案:

答案 0 :(得分:0)

分页库 版本3 现在可用,并支持CoroutinePagedList.BoundaryCallback现在为Deprecated,在这种情况下,我们需要使用RemoteMediator,它有一个suspend fun load用于处理Remote+Local分页