【问题标题】:How to inject data source factory from android pagination library?如何从android分页库中注入数据源工厂?
【发布时间】:2019-02-20 09:39:32
【问题描述】:

我正在使用分页库,我想将数据源注入到我的视图模型中。 我的工厂是这样的:

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.    

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

【问题讨论】:

  • 您的工厂代码看起来不错。可以分享dataSource并查看模型代码吗?
  • 编辑了我的问题
  • 对不起,我不知道真正的原因。但我猜你是在初始化 dataSourceFactory 之前访问数据源
  • 您是否在模块中提供数据源?
  • 没有。我在数据源工厂的 create() 方法中初始化数据源。这在第一个 sn-p 中描述。我应该为这家工厂写提供者吗?

标签: android kotlin dagger-2 android-paging dagger


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-04
    • 1970-01-01
    • 2022-06-30
    • 1970-01-01
    • 2022-08-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多