简体   繁体   English

如何从 DataSource.Factory 获取数据

[英]How to get data from DataSource.Factory

I have to call this method to get all the persons.我必须调用这个方法来获取所有的人。 I cannot modify this method at all.我根本无法修改此方法。

@Query("SELECT * FROM PERSON_TABLE ORDER BY NAME DESC"
abstract fun getElements(): DataSource.Factory<Int, Person>

Then in an Activity I am calling it like this:然后在一个Activity我这样称呼它:

override fun onCreate(...)
{
    ...

    val data = dao.getElements()
}

I want to get all the Person s, possibly as a list.我想得到所有的Person ,可能是一个列表。 How do I do this?我该怎么做呢?

I don't understand how DataSource.Factory<Int, Person> works.我不明白DataSource.Factory<Int, Person>是如何工作的。

According to the docs :根据文档

Typically, your UI code observes a LiveData object (or, if you're using RxJava2, a Flowable or Observable object), which resides in your app's ViewModel.通常,您的 UI 代码观察驻留在应用程序的 ViewModel 中的 LiveData 对象(或者,如果您使用 RxJava2,则观察 Flowable 或 Observable 对象)。 This observable object forms a connection between the presentation and contents of your app's list data.这个 observable 对象在你的应用列表数据的展示和内容之间形成了联系。

In order to create one of these observable PagedList objects, pass in an instance of DataSource.Factory to a LivePagedListBuilder or RxPagedListBuilder object.为了创建这些可观察的 PagedList 对象之一,请将 DataSource.Factory 的实例传递给 LivePagedListBuilder 或 RxPagedListBuilder 对象。 A DataSource object loads pages for a single PagedList. DataSource 对象为单个 PagedList 加载页面。 The factory class creates new instances of PagedList in response to content updates, such as database table invalidations and network refreshes.工厂类创建 PagedList 的新实例以响应内容更新,例如数据库表失效和网络刷新。 The Room persistence library can provide DataSource.Factory objects for you, or you can build your own. Room 持久性库可以为您提供 DataSource.Factory 对象,或者您可以构建自己的对象。

The sample code is as following:示例代码如下:

// The Int type argument corresponds to a PositionalDataSource object.
val data: DataSource.Factory<Int, Person> = dao.getElements()

val dataList: LiveData<PagedList<Person>> = LivePagedListBuilder(data, /* page size */ 20).build()

So you need to pass your DataSource.Factory<Int, Person> object to LivePagedListBuilder and at the end you will get LiveData<PagedList<Person>> which you can observe.所以你需要将你的DataSource.Factory<Int, Person>对象传递给LivePagedListBuilder ,最后你会得到LiveData<PagedList<Person>> ,你可以观察到。


After that you need to connect LiveData to a PagedListAdapter as shown in the following code snippet:之后,您需要LiveData 连接PagedListAdapter ,如以下代码片段所示:

private val adapter = YourDataAdapter()

override fun onCreate(savedInstanceState: Bundle?) {
    dataList.observe(this, Observer { adapter.submitList(it) })
}

The sample code of adapter you can find here .您可以在此处找到适配器的示例代码。

We use Datasource when we want to do pagination using the android paging component.当我们想使用 android 分页组件进行分页时,我们使用 Datasource。 there are so many ways to achieve it,有很多方法可以实现,

First implement paging library先实现分页库

implementation "android.arch.paging:runtime:2.1.0"

Now the most simple method to convert data source into LiveData> is this现在最简单的把数据源转换成LiveData>的方法就是这个

fun getElementsLiveData(): LiveData<PagedList<Person>> {

        val data = mDao.getElements()
        return LivePagedListBuilder(data, 10).build() // 10 is page size

}

you can also pass configuration instead on page size您还可以在页面大小上传递配置

    fun getElementsLiveData(): LiveData<PagedList<Person>> {

     val pagedListConfig = PagedList.Config.Builder()
        .setEnablePlaceholders(true)
        .setInitialLoadSizeHint(15)
        .setPageSize(10)
        .build()

        val data = mDao.getElements()
        return LivePagedListBuilder(data, pagedListConfig).build()

}

Now create your pager adapter and view holder like this现在像这样创建你的寻呼机适配器和视图持有者

    class ElementAdapter(
    private val clickListener: ClickListener
) : PagedListAdapter<Person, ElementViewHolder>(diffCallback) {

    override fun onBindViewHolder(holder: ElementViewHolder, position: Int) {
        val person = getItem(position)
        with(holder) {
             // bind your data here
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ElementViewHolder =
        ElementViewHolder(parent)

    companion object {
        /**
         * This diff callback informs the PagedListAdapter how to compute list differences when new
         * PagedLists arrive.
         */
        private val diffCallback = object : DiffUtil.ItemCallback<Person>() {
            override fun areItemsTheSame(oldItem: Person, newItem: Person): Boolean =
                oldItem.id == newItem.id

            override fun areContentsTheSame(oldItem: News, newItem: News): Boolean =
                oldItem.title == newItem.title
        }
    }
}

after that, in your activity or fragment you can simply observer the data change using viewmodel and submit your data to the adapter之后,在您的活动或片段中,您可以简单地使用 viewmodel 观察数据更改并将您的数据提交给适配器

 viewModel.getElementsLiveData().observer(this, Observer{pagedList->
  adaoter.submitList(pagedList)
 })

Adding to @Sergey 's answer, You can use PagedList<>.snapshot() to get as a regular list添加到@Sergey 的答案中,您可以使用PagedList<>.snapshot()获取常规列表

 // Get the DataSource from the database
 val dataSource: DataSource.Factory<Int, Person> = dao.getElements()

 // Get the dataSource as LiveData
 val data = dataSource.toLiveData(20 /* page size */)

 // In UI
 vm.data.observer(this, Observer{pagedList->
  // To get the pagedList as a regular list -
  val dataList = pagedList.snapshot()
 })

Note : The snapshot() function only gives you the currently available items in your pagedList.注意snapshot()函数只为您提供 pagedList 中当前可用的项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 房间本地单元测试 - 从 DataSource.Factory 查询 PagedList - Room Local Unit Test - Query PagedList from DataSource.Factory DataSource.Factory的create方法不会得到调用 - create method of DataSource.Factory doesn't get call 用于多个数据源的分页库 DataSource.Factory - Paging library DataSource.Factory for multiple data sources 无法从Android的分页中的DataSource.Factory获得toLiveData - toLiveData not available from DataSource.Factory in Android's Paging 如何测试返回DataSource.Factory的Dao方法? - How to test Dao methods which return DataSource.Factory? Android Room 在使用 DataSource.Factory 时如何按文本搜索? - Android Room how to search by text when using DataSource.Factory? 具有多视图 RecyclerView 的 Room DataSource.Factory - Room DataSource.Factory with multiple view RecyclerView Android 分页库 - Map 房间 DataSource.Factory&lt;*, DatabaseModel&gt; 到 DataSource.Factory&lt;*, PresenterModel&gt; - Android Paging Library - Map Room DataSource.Factory<*, DatabaseModel> to DataSource.Factory<*, PresenterModel> Android体系结构组件分页DataSource.Factory错误 - Android architecture components paging DataSource.Factory error 自定义构造函数PageKeyedDataSource()在分页库的datasource.factory()中崩溃应用程序 - Custom constructor PageKeyedDataSource() crashes app in datasource.factory() of paging library
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM