如何从DataSource.Factory获取数据 [英] How to get data from DataSource.Factory

查看:434
本文介绍了如何从DataSource.Factory获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须调用此方法才能获得所有人员.我根本无法修改此方法.

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

然后在Activity中,我这样称呼它:

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

    val data = dao.getElements()
}

我想获取所有的Person,可能是列表.我该怎么做?

我不明白DataSource.Factory<Int, Person>的工作原理.

解决方案

根据连接 LiveData PagedListAdapter,如以下代码段所示:

private val adapter = YourDataAdapter()

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

您可以在此处找到适配器的示例代码. /p>

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:

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

    val data = dao.getElements()
}

I want to get all the Persons, possibly as a list. How do I do this?

I don't understand how DataSource.Factory<Int, Person> works.

解决方案

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. This observable object forms a connection between the presentation and contents of your app's list data.

In order to create one of these observable PagedList objects, pass in an instance of DataSource.Factory to a LivePagedListBuilder or RxPagedListBuilder object. A DataSource object loads pages for a single PagedList. The factory class creates new instances of PagedList in response to content updates, such as database table invalidations and network refreshes. The Room persistence library can provide DataSource.Factory objects for you, or you can build your own.

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.


After that you need to connect LiveData to a PagedListAdapter as shown in the following code snippet:

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.

这篇关于如何从DataSource.Factory获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆