gpt4 book ai didi

android - 如何从android分页库中注入(inject)数据源工厂?

转载 作者:行者123 更新时间:2023-12-02 12:26:59 25 4
gpt4 key购买 nike

我正在使用分页库,我想将数据源注入(inject)我的 View 模型。我的工厂看起来像:

class ArticleDataSourceFactory @Inject constructor(
val articleRepository: ArticleRepository
) : DataSource.Factory<Long, Article>() {

override fun create(): DataSource<Long, Article> {
return ArticleDateKeyedDataSource(articleRepository)
}
}

我的数据源:

class ArticleDateKeyedDataSource(
private val repository: ArticleRepository
) : ItemKeyedDataSource<Long, Article>() {
override fun loadInitial(params: LoadInitialParams<Long>, callback: LoadInitialCallback<Article>) {
val articles = repository.getInitial(params.requestedInitialKey!!, params.requestedLoadSize)
callback.onResult(articles)
}

override fun loadAfter(params: LoadParams<Long>, callback: LoadCallback<Article>) {
val articles = repository.getAfter(params.key, params.requestedLoadSize)
callback.onResult(articles)
}

override fun loadBefore(params: LoadParams<Long>, callback: LoadCallback<Article>) {
val articles = repository.getBefore(params.key, params.requestedLoadSize)
callback.onResult(articles)
}

override fun getKey(item: Article): Long {
return item.createdAt
}
}

还有我的 ViewModel:

class ArticleFragmentViewModel @Inject constructor(
private val dataSourceFactory: ArticleDataSourceFactory
) : BaseViewModel() {

var initialArticlePosition = 0L

val navigateToArticleDetails: MutableLiveData<SingleEvent<Long>> = MutableLiveData()

val articlesLiveList: LiveData<PagedList<Article>>
get() {
val config = PagedList.Config.Builder()
.setEnablePlaceholders(false)
.setPageSize(5)
.build()

return LivePagedListBuilder(dataSourceFactory, config)
.setInitialLoadKey(initialArticlePosition)
.setFetchExecutor(Executors.newSingleThreadExecutor())
.build()
}


fun onArticleSelected(createdAt: Long) {
navigateToArticleDetails.value = SingleEvent(createdAt)
}
}

重建后,我得到一个错误:

error: cannot access DataSource
class file for androidx.paging.DataSource not found
Consult the following stack trace for details.

这是什么意思?我不知道,我做错了什么。例如,我注入(inject)存储库没有问题。

最佳答案

你用过安卓模块吗?您可能需要在基础模块中使用 api 依赖项,例如

api "androidx.paging:paging-runtime-ktx:$paging_version"

还有类似的问题https://stackoverflow.com/a/47128596/5934119

关于android - 如何从android分页库中注入(inject)数据源工厂?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54783112/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com