Architecture -- Paging

简介: 1. Pading1). 简介分页库使您可以更轻松地在应用程序的RecyclerView中逐步和优雅地加载数据。许多应用程序使用包含大量项目的数据源中的数据,但一次只显示一小部分。

1. Pading

1). 简介

分页库使您可以更轻松地在应用程序的RecyclerView中逐步和优雅地加载数据。许多应用程序使用包含大量项目的数据源中的数据,但一次只显示一小部分。分页库可帮助您的应用观察并显示此数据的合理子集。 此功能有几个优点:
数据请求消耗的网络带宽更少,系统资源更少。 拥有计量或小数据计划的用户会欣赏这些具有数据意识的应用程序。
即使在数据更新和刷新期间,应用程序仍会继续快速响应用户输入。

2). 依赖
ext {
  paging_version = "1.0.0-alpha6"
}

dependencies {
  // paging
  implementation "android.arch.paging:runtime:$paging_version"
  implementation("android.arch.paging:rxjava2:1.0.0-rc1") {
    exclude group: 'android.arch.paging', module: 'common'
  }
}
3). DataSource
  • PageKeyedDataSource: 如果您加载的页面嵌入了下一个/上一个键,请使用PageKeyedDataSource。 例如,如果您从网络中获取社交媒体帖子,则可能需要将nextPage令牌从一个加载传递到后续加载。
  • ItemKeyedDataSource: 如果需要使用项目N中的数据来获取项目N + 1,请使用ItemKeyedDataSource。 例如,如果您要为讨论应用程序提取线程注释,则可能需要传递最后一条注释的ID以获取下一条注释的内容。
  • PositionalDataSource: 如果需要从数据存储中选择的任何位置获取数据页,请使用PositionalDataSource。 此类支持从您选择的任何位置开始请求一组数据项。 例如,请求可能返回以位置1200开头的20个数据项。

2. Paging + Room

1). 创建Room数据实体
/**
 * Room 实体
 * Created by mazaiting on 2018/7/25.
 */
@Entity(tableName = "student")
data class StudentRoom(
        var name: String
) {
  @PrimaryKey(autoGenerate = true)
  var id: Int = 0
}
2). 创建数据库DAO
/**
 * 数据库操作对象
 * Created by mazaiting on 2018/7/26.
 */
@Dao
interface StudentDao {
  /**
   * 插入数据
   */
  @Insert
  fun insert(student: List<StudentRoom>)
  
  /**
   * 查询所有学生
   */
  @Query("SELECT * FROM student ORDER BY id DESC")
  fun findAllStudents() : DataSource.Factory<Int, StudentRoom>
}
3). 创建数据库
/**
 * 数据库
 * Created by mazaiting on 2018/7/26.
 */
@Database(entities = arrayOf(StudentRoom::class), version = 1)
abstract class StudentDatabase : RoomDatabase() {
  // 获取DAO
  abstract fun studentDao() : StudentDao
}
4). 创建ViewModel
class StudentViewModel : ViewModel() {
  /**
   * 查询所有学生
   */
  fun findAllStudents(application: Application): LiveData<PagedList<StudentRoom>> {
    val db = Room.databaseBuilder(application, StudentDatabase::class.java, "PAGING").build()
    val dao = db.studentDao()
//    val list: LiveData<PagedList<StudentRoom>> =
//            LivePagedListBuilder(dao.findAllStudents(), 15).build()
    val list: LiveData<PagedList<StudentRoom>> =
            LivePagedListBuilder(dao.findAllStudents(),
                    PagedList.Config.Builder()
                            // 设置分页加载数量
                            .setPageSize(PAGE_SIZE)
                            // 配置是否启动PlaceHolders
                            .setEnablePlaceholders(ENABLE_PLACE_HOLDERS)
                            // 初始化加载数量
                            .setInitialLoadSizeHint(PAGE_SIZE)
                            .build()
                    ).build()
    return list
  }
}
5). 创建RecycleView适配器
/**
 * Student适配器
 * Created by mazaiting on 2018/7/26.
 */
class StudentAdapter : PagedListAdapter<StudentRoom, StudentAdapter.StudentViewHolder>(DIFF_CALLBACK) {
  override fun onBindViewHolder(holder: StudentViewHolder, position: Int) =
          holder.bindTo(getItem(position))
  
  override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): StudentViewHolder =
          StudentViewHolder(parent)
    
  companion object {
    // Item回调
    private val DIFF_CALLBACK = object : DiffUtil.ItemCallback<StudentRoom>() {
      // 条目是否相同
      override fun areItemsTheSame(oldItem: StudentRoom, newItem: StudentRoom): Boolean = oldItem.id == newItem.id
      // 内容是否相同
      override fun areContentsTheSame(oldItem: StudentRoom, newItem: StudentRoom): Boolean = oldItem == newItem
    }
  }
  
  class StudentViewHolder(parent: ViewGroup) : RecyclerView.ViewHolder(
          // 加载布局
          LayoutInflater.from(parent.context).inflate(R.layout.item_student, parent, false)
  ) {
    // 查找view
    private val nameView = itemView.findViewById<TextView>(R.id.tv_name)
    // 创建数据
    private var student: StudentRoom? = null
  
    /**
     * 绑定数据
     */
    fun bindTo(student: StudentRoom?) {
      this.student = student
      // 设置文本
      nameView.text = student?.name
    }
  }
}
6). Activity代码
class PagingRoomActivity : AppCompatActivity() {
  /**
   * 懒加载ViewModel
   */
  private val viewModel by lazy {
    ViewModelProviders.of(this).get(StudentViewModel::class.java)
  }
  
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_paging_room)
    // 创建适配器
    val adapter = StudentAdapter()
    // 设置布局管理者
    rv_show.layoutManager = LinearLayoutManager(this)
    // 设置适配器
    rv_show.adapter = adapter
    // 数据变化时更新列表
    viewModel.findAllStudents(application).observe(this, Observer { adapter.submitList(it) })
  }
}

3. Pading + 自定义数据源

1). 创建数据实体类
/**
 * 数据实体类
 * Created by mazaiting on 2018/7/26.
 */
data class Student (
     val id: Int,
     val name: String
)
2). 创建适配器
/**
 * 适配器
 * Created by mazaiting on 2018/7/26.
 */
class StudentAdapter : PagedListAdapter<Student, StudentAdapter.StudentViewHolder>(DIFF_CALLBACK) {
  override fun onBindViewHolder(holder: StudentViewHolder, position: Int) =
          holder.bindTo(getItem(position))
  
  override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): StudentViewHolder =
          StudentViewHolder(parent)
  
  companion object {
    /**
     * 条目不同回调
     */
    private val DIFF_CALLBACK = object : DiffUtil.ItemCallback<Student>() {
      override fun areItemsTheSame(oldItem: Student, newItem: Student): Boolean = oldItem.id == newItem.id
      
      override fun areContentsTheSame(oldItem: Student, newItem: Student): Boolean = oldItem == newItem
    }
  }
  
  class StudentViewHolder(parent: ViewGroup) : RecyclerView.ViewHolder(
          // 加载布局
          LayoutInflater.from(parent.context).inflate(R.layout.item_student, parent, false)
  ) {
    // 获取view
    private val nameView = itemView.findViewById<TextView>(R.id.tv_name)
    private var student: Student? = null
  
    /**
     * 绑定数据
     */
    fun bindTo(student: Student?) {
      this.student = student
      nameView.text = student?.name
    }
  }
}
3). 创建数据源
private val CHEESE_DATA = arrayListOf(
        "Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam", "Abondance", "Ackawi",
        "Acorn", "Adelost", "Affidelice au Chablis", "Afuega'l Pitu", "Airag", "Airedale",
        "Aisy Cendre", "Allgauer Emmentaler", "Alverca", "Ambert", "American Cheese",
        "Ami du Chambertin", "Anejo Enchilado", "Anneau du Vic-Bilh", "Anthoriro", "Appenzell",
        "Aragon", "Ardi Gasna", "Ardrahan", "Armenian String", "Aromes au Gene de Marc",
        "Asadero", "Asiago", "Aubisque Pyrenees", "Autun", "Avaxtskyr", "Baby Swiss",
        "Babybel", "Baguette Laonnaise", "Bakers", "Baladi", "Balaton", "Bandal", "Banon",
        "Barry's Bay Cheddar", "Basing", "Basket Cheese", "Bath Cheese", "Bavarian Bergkase",
        "Baylough", "Beaufort", "Beauvoorde", "Beenleigh Blue", "Beer Cheese", "Bel Paese",
        "Bergader", "Bergere Bleue", "Berkswell", "Beyaz Peynir", "Bierkase", "Bishop Kennedy",
        "Blarney", "Bleu d'Auvergne", "Bleu de Gex", "Bleu de Laqueuille",
        "Bleu de Septmoncel", "Bleu Des Causses", "Blue", "Blue Castello", "Blue Rathgore",
        "Blue Vein (Australian)", "Blue Vein Cheeses", "Bocconcini", "Bocconcini (Australian)"
)
/**
 * 数据源
 * Created by mazaiting on 2018/7/26.
 */
class StudentDataSource : PositionalDataSource<Student>() {
  /**
   * 范围加载
   */
  override fun loadRange(params: LoadRangeParams, callback: LoadRangeCallback<Student>) {
    // 回调结果
    callback.onResult(loadRangeInternal(params.startPosition, params.loadSize))
  }
  
  /**
   * 加载初始化
   */
  override fun loadInitial(params: LoadInitialParams, callback: LoadInitialCallback<Student>) {
    // 全部数据数量
    val totalCount = computeCount()
    // 当前位置
    val position = computeInitialLoadPosition(params, totalCount)
    // 加载数量
    val loadSize = computeInitialLoadSize(params, position, totalCount)
    // 回调结果
    callback.onResult(loadRangeInternal(position, loadSize), position, totalCount)
  }
  
  /**
   * 加载网络数据
   */
  private fun loadRangeInternal(position: Int, loadSize: Int): MutableList<Student> {
    // 创建列表
    val list = arrayListOf<Student>()
    // 遍历列表数据
    CHEESE_DATA.mapIndexed { index, text -> list.add(Student(index, text)) }
    // 设置加载数据
    var size = loadSize
    // 判断加载的位置是否大于总数据
    if (position >= computeCount()) {
      // 返回空数据
      return Collections.emptyList()
    }
    // 判断总条数是否大于计算的数据
    if (position + loadSize > computeCount()) {
      size = computeCount() - position - 1
    }
//    L.e("${computeCount()}:: $position :: $size" )
    // 返回子列表
    return list.subList(position, size + position)
  }
  
  /**
   * 总条数
   */
  private fun computeCount(): Int = CHEESE_DATA.size
  
}
4). ViewModel中创建获取数据方法
  /**
   * 查询本地数据
   */
  fun loadNativeStudent(): LiveData<PagedList<Student>> {
    val dataSourceFactory = DataSource.Factory<Int, Student> { StudentDataSource() }
    val list: LiveData<PagedList<Student>> =
            LivePagedListBuilder(dataSourceFactory,
                    PagedList.Config.Builder()
                            .setPageSize(PAGE_SIZE)
                            .setEnablePlaceholders(ENABLE_PLACE_HOLDERS)
                            .setInitialLoadSizeHint(PAGE_SIZE)
                            .build()
            ).build()
    return list
  }
5). Activity代码
class PagingCustomActivity : AppCompatActivity() {
  /**
   * 懒加载ViewModel
   */
  private val viewModel by lazy {
    ViewModelProviders.of(this).get(StudentViewModel::class.java)
  }
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_paging_custom)
    // 创建适配器
    val adapter = StudentAdapter()
    // 设置布局管理者
    rv_show.layoutManager = LinearLayoutManager(this)
    // 设置适配器
    rv_show.adapter = adapter
    // 数据改变通知RecyclerView更新
    viewModel.loadNativeStudent().observe(this, Observer { adapter.submitList(it) })
  }
}
6). 原文链接
7). 代码下载
目录
相关文章
|
设计模式 缓存 监控
译|Design patterns for container-based distributed systems(下)
译|Design patterns for container-based distributed systems(下)
66 0
PAT (Advanced Level) Practice:1~3题
​ ✨欢迎您的订阅✨ PAT乙级专栏(更新完毕): 👉🏻【Basic Level】👈🏻 PAT甲级专栏(更新ing): 👉🏻【Advanced Level】👈🏻 ​
PAT (Advanced Level) Practice:1~3题
|
移动开发 C语言
PAT (Advanced Level) Practice 1042 Shuffling Machine (20 分)
PAT (Advanced Level) Practice 1042 Shuffling Machine (20 分)
88 0
|
存储 缓存 API
Paging3简单理解
Paging3简单理解
481 0
Paging3简单理解
PAT (Advanced Level) Practice - 1022 Digital Library(30 分)
PAT (Advanced Level) Practice - 1022 Digital Library(30 分)
115 0
PAT (Advanced Level) Practice - 1112 Stucked Keyboard(20 分)
PAT (Advanced Level) Practice - 1112 Stucked Keyboard(20 分)
122 0
|
测试技术
Note tool
Sent: Monday, March 23, 2015 2:56 PM https://dewdfgwd:2030/sap/bc/ui5_ui5/sap/znotetool/index.html?sap-client=001&sap-ui-language=EN&sap-ui-appcache=false 把Opportunity,(或者lead,Appointment,task)ID输入,点submit,就能看到下面挂着的note全部的technical information了 后台只能连AG3哈,这个是拿来做单元测试的。 GM6/001 tcode SE80:
Note tool
|
JavaScript IDE 数据可视化
paasone的创新(2):separated langsysdemo ecosystem及demo driven debug
本文关键字:visual demo driven debugging,engitor编程,更好用的qtquick
460 0
paasone的创新(2):separated langsysdemo ecosystem及demo driven debug
|
Java 虚拟化 C++
Stack based vs Register based Virtual Machine Architecture
进程虚拟机简介 一个虚拟机是对原生操作系统的一个高层次的抽象,目的是为了模拟物理机器,本文所谈论的是基于进程的虚拟机,而不是基于系统的虚拟机,基于系统的虚拟机可以用来在同一个平台下去运行多个不同的硬件架构的操作系统,常见的有kvm,xen,vmware等,而基于进程的虚拟机常见的有JVM,PVM(python虚拟机)等,java和python的解释器将java和python的代码编译成JVM和P
3652 0
|
Android开发 Java Kotlin
Architecture -- WorkManager
1. WorkManager 1). 简介 其实就是"管理一些要在后台工作的任务, -- 即使你的应用没启动也能保证任务能被执行",WorkManager在底层, 会根据你的设备情况, 选用JobScheduler, Firebase的JobDispatcher, 或是AlarmManager。
896 0