android_jetpack_paging使用篇(比较规范一套流程)

转载自: https://zhuanlan.zhihu.com/p/57230158

在本教程中,我将向您展示如何在Android的应用程序中使用Android的架构组件中的分页库和房支持的数据库。

您将学习如何使用Paging库从Room支持的数据库高效加载大型数据集 - 在RecyclerView中滚动时为您的用户提供更流畅的体验。

什么是分页库?

Paging库是添加到Architecture Components的另一个库。该库有助于有效地管理大型数据集的加载和显示RecyclerView。根据官方文件:

分页库使您可以更轻松地在应用程序中逐渐和优雅地加载数据RecyclerView

如果Android的应用程序的任何部分要从本地或远程数据源显示大型数据集,但一次只显示部分数据集,则应考虑使用分页库。这有助于提高应用的性能!

那么为什么要使用寻呼库?

既然您已经看过寻呼库的介绍,您可能会问,为什么要使用它?以下是您应该考虑在加载大型数据集时使用它的一些原因RecyclerView

  • 它不会请求不需要的数据。当用户滚动列表时,此库仅请求用户可见的数据。
  • 节省用户的电池并消耗更少的带宽。因为它只请求所需的数据,所以这节省了一些设备资源。

在处理大量数据时效率不高,因为底层数据源会检索所有数据,即使只有一部分数据要显示给用户。在这种情况下,我们应该考虑分页数据。

1.创建Android Studio项目

启动Android Studio 3并创建一个名为空活动的新项目 MainActivity。一定要检查包含Kotlin支持

Android Studio创建项目屏幕

2.添加架构组件

创建新项目后,在的build.gradle中添加以下依赖。在本教程中,我们使用的是最新的寻呼库版本1.0.1,而房间是1.1.1(截至撰写本文时)。

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "android.arch.persistence.room:runtime:1.1.1"
    kapt "android.arch.persistence.room:compiler:1.1.1"
    implementation "android.arch.paging:runtime:1.0.1"
    implementation "com.android.support:recyclerview-v7:27.1.1"
}

这些工件可在谷歌的Maven的存储库中找到。

allprojects {
    repositories {
        google()
        jcenter()
    }
}

通过添加依赖项,我们已经教过摇篮如何查找库。确保在添加项目后记得同步项目。

3.创建实体

创建一个新的科特林数据类人员为简单起见,我们的人实体只有两个字段:

一个唯一的ID(id)
人的名字(name)另外
,包括一个toString(简单返回的方法名称。

import android.arch.persistence.room.Entity
import android.arch.persistence.room.PrimaryKey
 
@Entity(tableName = "persons")
data class Person(
        @PrimaryKey val id: String,
        val name: String
) {
    override fun toString() = name
}

4.创建道

如您所知,我们需要使用房库来访问应用程序的数据,我们需要数据访问对象(DAO)。在我们自己的案例中,我们创建了一个PersonDao。

import android.arch.lifecycle.LiveData
import android.arch.paging.DataSource
import android.arch.persistence.room.Dao
import android.arch.persistence.room.Delete
import android.arch.persistence.room.Insert
import android.arch.persistence.room.Query
 
@Dao
interface PersonDao {
 
    @Query("SELECT * FROM persons")
    fun getAll(): LiveData<List<Person>>
 
    @Query("SELECT * FROM persons")
    fun getAllPaged(): DataSource.Factory<Int, Person>
 
    @Insert
    fun insertAll(persons: List<Person>)
 
    @Delete
    fun delete(person: Person)
}

在我们PersonDao班上,我们有两种@Query方法。其中之一是getAll(),它返回一个LiveData包含人对象列表的东西。另一个是getAllPaged(),返回一个DataSource.Factory。

根据官方文件,该数据源课程是:

用于将快照数据页面加载到的基类PagedList。
一个PagedList是一种List在Android中显示分页数据的特殊类型:

PagedList是一个List,它从中以块(页)加载其数据DataSource。可以使用,访问项目get(int),并可以触发进一步加载loadAround(int)。
我们Factory在DataSource类中调用静态方法,该方法用作工厂(创建对象而不必指定将要创建的对象的确切类)的DataSource此静态方法有两种数据类型:

标识项目的关键数据源。请注意,对于房间查询,页面是编号的 - 因此我们将其整个用户页面标识符类型。使用Paging库可以使用“键控”页面,但房间目前不提供.DataSources
加载的列表中的项目或实体(POJO)的类型。

5.创建数据库

这是我们的房间数据库类的AppDatabase样子:

import android.arch.persistence.db.SupportSQLiteDatabase
import android.arch.persistence.room.Database
import android.arch.persistence.room.Room
import android.arch.persistence.room.RoomDatabase
import android.content.Context
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import com.chikeandroid.pagingtutsplus.utils.DATABASE_NAME
import com.chikeandroid.pagingtutsplus.workers.SeedDatabaseWorker
 
@Database(entities = [Person::class], version = 1, exportSchema = false)
abstract class AppDatabase : RoomDatabase() {
    abstract fun personDao(): PersonDao
 
    companion object {
 
        // For Singleton instantiation
        @Volatile private var instance: AppDatabase? = null
 
        fun getInstance(context: Context): AppDatabase {
            return instance ?: synchronized(this) {
                instance
                        ?: buildDatabase(context).also { instance = it }
            }
        }
 
        private fun buildDatabase(context: Context): AppDatabase {
            return Room.databaseBuilder(context, AppDatabase::class.java, DATABASE_NAME)
                    .addCallback(object : RoomDatabase.Callback() {
                        override fun onCreate(db: SupportSQLiteDatabase) {
                            super.onCreate(db)
                            val request = OneTimeWorkRequestBuilder<SeedDatabaseWorker>().build()
                            WorkManager.getInstance()?.enqueue(request)
                        }
                    })
                    .build()
        }
    }
}

在这里,我们创建了一个数据库实例,并使用新的WorkManager API预先填充了数据。请注意,预先填充的数据只是1000个名称的列表(深入了解提供的示例源代码以了解更多信息)。

6.创建ViewModel

为了让我们以生命周期意识的方式存储,观察和提供数据,我们需要一个ViewModel。我们的PersonsViewModel,扩展它了AndroidViewModel类,是要作为我们的ViewModel

import android.app.Application
import android.arch.lifecycle.AndroidViewModel
import android.arch.lifecycle.LiveData
import android.arch.paging.DataSource
import android.arch.paging.LivePagedListBuilder
import android.arch.paging.PagedList
import com.chikeandroid.pagingtutsplus.data.AppDatabase
import com.chikeandroid.pagingtutsplus.data.Person
 
class PersonsViewModel constructor(application: Application)
    : AndroidViewModel(application) {
 
    private var personsLiveData: LiveData<PagedList<Person>>
 
    init {
        val factory: DataSource.Factory<Int, Person> =
        AppDatabase.getInstance(getApplication()).personDao().getAllPaged()
 
        val pagedListBuilder: LivePagedListBuilder<Int, Person>  = LivePagedListBuilder<Int, Person>(factory,
                50)
        personsLiveData = pagedListBuilder.build()
    }
 
    fun getPersonsLiveData() = personsLiveData
}

在这个类中,我们有一个名为的字段personsLiveData。这个字段是一个简单的LiveData持有一个PagedList的人对象。因为这是一个LiveData,我们的UI(活动或片段)将通过调用getter方法来观察这些数据getPersonsLiveData()。

我们人员在这里块初始化。在这个块中,我们DataSource.Factory通过调用对象的AppDatabase单例来获得PersonDao。当我们得到这个对象时,我们打电话getAllPaged()。

。然后我们创建一个LivePagedListBuilder以下是官方文档中关于一的说明LivePagedListBuilder:

生成器LiveData ,给定一个DataSource.Factory和一个PagedList.Config。
我们提供构造函数a DataSource.Factory作为第一个参数,页面大小作为第二个参数(在我们自己的情况下,页面大小将为50)。通常,您应该选择一个大于您可能一次向用户显示的最大数量的大小。最后,我们打电话构建()给我们构建并返回给我们LiveData 。

7.创建PagedListAdapter

要PagedList在一中显示我们的数据RecyclerView,我们需要一个PagedListAdapter以下是官方文档中对此类的明确定义:

RecyclerView.Adapter用于从PagedLista中的s呈现分页数据的基类RecyclerView。
所以我们创建了一个PersonAdapter扩展PagedListAdapter。

import android.arch.paging.PagedListAdapter
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.chikeandroid.pagingtutsplus.R
import com.chikeandroid.pagingtutsplus.data.Person
import kotlinx.android.synthetic.main.item_person.view.*
 
class PersonAdapter(val context: Context) : PagedListAdapter<Person, PersonAdapter.PersonViewHolder>(PersonDiffCallback()) {
 
    override fun onBindViewHolder(holderPerson: PersonViewHolder, position: Int) {
        var person = getItem(position)
 
        if (person == null) {
            holderPerson.clear()
        } else {
            holderPerson.bind(person)
        }
    }
 
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PersonViewHolder {
        return PersonViewHolder(LayoutInflater.from(context).inflate(R.layout.item_person,
                parent, false))
    }
 
 
    class PersonViewHolder (view: View) : RecyclerView.ViewHolder(view) {
 
        var tvName: TextView = view.name
 
        fun bind(person: Person) {
            tvName.text = person.name
        }
 
        fun clear() {
            tvName.text = null
        }
 
    }
}

PagedListAdapter就像使用的任何其他子类一样使用RecyclerView.Adapter。换句话说,你必须实现方法onCreateViewHolder()和onBindViewHolder()。

要扩展PagedListAdapter抽象类,您必须提供其构造函数 - PageLists(这应该是一个普通的旧Java类:POJO)的类型,以及扩展ViewHolder适配器将使用的类的类。在我们的例子中,我们给它人,并PersonViewHolder分别作为第一和第二个参数。

请注意,PagedListAdapter需要将其传递DiffUtil.ItemCallback给PageListAdapter构造函数.DiffUtil是一个RecyclerView实用程序类,可以计算两个列表之间的差异,并输出将第一个列表转换为第二个列表的更新操作列表.ItemCallback是一个内部抽象静态类(内部DiffUtil),用于计算列表中两个非空项之间的差异。

具体来说,我们提供PersonDiffCallback给我们的PagedListAdapter构造函数。

import android.support.v7.util.DiffUtil
import com.chikeandroid.pagingtutsplus.data.Person
 
class PersonDiffCallback : DiffUtil.ItemCallback<Person>() {
 
    override fun areItemsTheSame(oldItem: Person, newItem: Person): Boolean {
        return oldItem.id == newItem.id
    }
 
    override fun areContentsTheSame(oldItem: Person?, newItem: Person?): Boolean {
        return oldItem == newItem
    }
}

因为我们正在实现DiffUtil.ItemCallback,所以我们必须实现两种方法:areItemsTheSame()和areContentsTheSame()。

areItemsTheSame调用以检查两个对象是否代表同一个项目。例如,如果您的项目具有唯一ID,则此方法应检查其ID相等.TRUE如果两个项表示相同的对象或假它们不同,则此方法返回。
areContentsTheSame调用以检查两个项目是否具有相同的数据.TRUE如果项目的内容相同或者虚假它们不同,则此方法返回。
我们的PersonViewHolder内心阶层只是一个典型的RecyclerView.ViewHolder。它负责根据需要将数据从我们的模型绑定到列表中的行的小部件中。

class PersonAdapter(val context: Context) : PagedListAdapter<Person, PersonAdapter.PersonViewHolder>(PersonDiffCallback()) {
     
    // ... 
     
    class PersonViewHolder (view: View) : RecyclerView.ViewHolder(view) {
 
        var tvName: TextView = view.name
 
        fun bind(person: Person) {
            tvName.text = person.name
        }
 
        fun clear() {
            tvName.text = null
        }
 
    }
}

8.显示结果

在我们的onCreate()的MainActivity,我们只是做了以下:

视图模型使用实用程序类初始化我们的字段ViewModelProviders
创建一个实例PersonAdapter
配置我们的RecyclerView
绑定PersonAdapter到RecyclerView
观察LiveData并通过调用将PagedList对象提交给PersonAdaptersubmitList()

import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProviders
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.RecyclerView
import com.chikeandroid.pagingtutsplus.adapter.PersonAdapter
import com.chikeandroid.pagingtutsplus.viewmodels.PersonsViewModel
 
class MainActivity : AppCompatActivity() {
 
    private lateinit var viewModel: PersonsViewModel
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
 
        viewModel = ViewModelProviders.of(this).get(PersonsViewModel::class.java)
 
        val adapter = PersonAdapter(this)
        findViewById<RecyclerView>(R.id.name_list).adapter = adapter
 
        subscribeUi(adapter)
    }
 
    private fun subscribeUi(adapter: PersonAdapter) {
        viewModel.getPersonLiveData().observe(this, Observer { names ->
            if (names != null) adapter.submitList(names)
        })
    }
}

最后,当您运行应用程序时,结果如下:

教程结果截图

滚动时,房间可以通过一次加载50项目个并将它们提供给我们PersonAdapter的子类来防止间隙PagingListAdapter。但请注意,并非所有数据源都会快速加载。加载速度还取决于Android的设备的处理能力。

9.与RxJava集成

如果您正在使用或想要在项目中使用RxJava,则分享库包含另一个有用的工具:RxPagedListBuilder。您使用此工件而不是 LivePagedListBuilderRxJava支持。

您只需创建一个实例 RxPagedListBuilder,提供与LivePagedListBuilder-the DataSource.Factory和页面大小相同的参数。然后调用 buildObservable()buildFlowable()返回一个ObservableFlowable您的PagedList分别。

显要式提供 Scheduler数据加载工作,请调用设置器方法 setFetchScheduler()。提供为了Scheduler查询查询结果(例如 AndroidSchedulers.mainThread()),只需拨打电话即可setNotifyScheduler()。默认情况下,setNotifyScheduler()默认为UI线程,setFetchScheduler()默认为I / O线程池。

结论

在本教程中,您学习了如何使用Room的Android架构组件(Android Jetpack的一部分)轻松使用Paging组件。这有助于我们有效地从本地数据库加载大型数据集,以便在滚动浏览列表时实现更流畅的用户体验RecyclerView。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值