如何从Android分页库注入数据源工厂?

问题描述 投票:1回答:1

我正在使用分页库,我想将数据源注入到我的viewmodel中。我的工厂看起来像:

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.    

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

android kotlin dagger-2 android-paging dagger
1个回答
0
投票

您使用Android模块吗?您可能需要在基本模块中使用api依赖项,例如

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

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

© www.soinside.com 2019 - 2024. All rights reserved.