Architecture -- Paging

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). 代码下载
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,273评论 19 139
  • 应用开发者面临的常见问题 共同的构建原则 推荐应用架构构建用户界面获取数据连接ViewModel和存储库缓存数据保...
    yyg阅读 3,060评论 0 0
  • 1.ios高性能编程 (1).内层 最小的内层平均值和峰值(2).耗电量 高效的算法和数据结构(3).初始化时...
    欧辰_OSR阅读 30,084评论 8 265
  • 丢掉50件不同种类的东西,在3个月里,确实有助于整理生活吧,而后面半句纯属鼓励。 这里就开始记录: 1、旧衣服。最...
    绿杨烟外阅读 3,593评论 0 3
  • 今天是写做的第一天,万事开头难,嘿嘿。其实写起来可能也没那么难。 已经开始上时间管理课程了,坚定了早上五点多起床的...
    周周的果子阅读 1,756评论 0 0

友情链接更多精彩内容