Android Paging3 – How to Auto Scoll to Bottom at Statup and When New Data is Added

In my sample app I use Paging3 to show a list of students (by page), I want the RecyclerView to show the last page and auto-scroll-to-bottom. My setup is like this:

PagingSource:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>class StudentPagingSource(
private val studentDao: StudentDao
) : PagingSource<Int, Student>() {
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Student> {
val totalCount = studentDao.getStudentsCount()
val initialPage = totalCount / params.loadSize //<- the last page
val page = params.key ?: initialPage
return try {
val students = studentDao.getPagedStudents(params.loadSize, page * params.loadSize)
LoadResult.Page(
data = students,
prevKey = if (page == 0) null else page - 1,
nextKey = if (students.isEmpty()) null else page + 1
)
} catch (e: Exception) {
LoadResult.Error(e)
}
}
override fun getRefreshKey(state: PagingState<Int, Student>): Int? {
return state.anchorPosition?.let {
val anchorPage = state.closestPageToPosition(it)
anchorPage?.prevKey?.plus(1) ?: anchorPage?.nextKey?.minus(1)
}
}
}
</code>
<code>class StudentPagingSource( private val studentDao: StudentDao ) : PagingSource<Int, Student>() { override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Student> { val totalCount = studentDao.getStudentsCount() val initialPage = totalCount / params.loadSize //<- the last page val page = params.key ?: initialPage return try { val students = studentDao.getPagedStudents(params.loadSize, page * params.loadSize) LoadResult.Page( data = students, prevKey = if (page == 0) null else page - 1, nextKey = if (students.isEmpty()) null else page + 1 ) } catch (e: Exception) { LoadResult.Error(e) } } override fun getRefreshKey(state: PagingState<Int, Student>): Int? { return state.anchorPosition?.let { val anchorPage = state.closestPageToPosition(it) anchorPage?.prevKey?.plus(1) ?: anchorPage?.nextKey?.minus(1) } } } </code>
class StudentPagingSource(
    private val studentDao: StudentDao
) : PagingSource<Int, Student>() {
    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Student> {
        val totalCount = studentDao.getStudentsCount()
        val initialPage = totalCount / params.loadSize    //<- the last page
        val page = params.key ?: initialPage

        return try {
            val students = studentDao.getPagedStudents(params.loadSize, page * params.loadSize)

            LoadResult.Page(
                data = students,
                prevKey = if (page == 0) null else page - 1,
                nextKey = if (students.isEmpty()) null else page + 1
            )
        } catch (e: Exception) {
            LoadResult.Error(e)
        }
    }

    override fun getRefreshKey(state: PagingState<Int, Student>): Int? {
        return state.anchorPosition?.let {
            val anchorPage = state.closestPageToPosition(it)

            anchorPage?.prevKey?.plus(1) ?: anchorPage?.nextKey?.minus(1)
        }
    }
}

Repository:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>class StudentRepository(
database: StudentDatabase
) {
companion object {
const val PAGE_SIZE = 30
}
private val studentDao = database.studentDao
fun getPagedStudents(): Flow<PagingData<Student>> {
val pager = Pager(
config = PagingConfig(
pageSize = PAGE_SIZE,
enablePlaceholders = false,
initialLoadSize = PAGE_SIZE
),
pagingSourceFactory = { StudentPagingSource(studentDao) }
)
return pager.flow
}
suspend fun saveStudents(vararg student: Student) = studentDao.insert(*student)
}
</code>
<code>class StudentRepository( database: StudentDatabase ) { companion object { const val PAGE_SIZE = 30 } private val studentDao = database.studentDao fun getPagedStudents(): Flow<PagingData<Student>> { val pager = Pager( config = PagingConfig( pageSize = PAGE_SIZE, enablePlaceholders = false, initialLoadSize = PAGE_SIZE ), pagingSourceFactory = { StudentPagingSource(studentDao) } ) return pager.flow } suspend fun saveStudents(vararg student: Student) = studentDao.insert(*student) } </code>
class StudentRepository(
    database: StudentDatabase
) {
    companion object {
        const val PAGE_SIZE = 30
    }

    private val studentDao = database.studentDao

    fun getPagedStudents(): Flow<PagingData<Student>> {
        val pager = Pager(
            config = PagingConfig(
                pageSize = PAGE_SIZE,
                enablePlaceholders = false,
                initialLoadSize = PAGE_SIZE
            ),
            pagingSourceFactory = { StudentPagingSource(studentDao) }
        )

        return pager.flow
    }

    suspend fun saveStudents(vararg student: Student) = studentDao.insert(*student)
}

ViewModel:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>class FirstViewModel(
application: Application,
private val studentRepository: StudentRepository
) : AndroidViewModel(application) {
private val uiScope = viewModelScope
val students = studentRepository.getPagedStudents().cachedIn(uiScope)
}
</code>
<code>class FirstViewModel( application: Application, private val studentRepository: StudentRepository ) : AndroidViewModel(application) { private val uiScope = viewModelScope val students = studentRepository.getPagedStudents().cachedIn(uiScope) } </code>
class FirstViewModel(
    application: Application,
    private val studentRepository: StudentRepository
) : AndroidViewModel(application) {
    private val uiScope = viewModelScope

    val students = studentRepository.getPagedStudents().cachedIn(uiScope)
}

Fragment:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_first, container, false)
studentAdapter = getStudentAdapter()
binding.viewModel = viewModel
binding.lifecycleOwner = viewLifecycleOwner
setupOptionsMenu()
binding.recyclerView.adapter = studentAdapter
viewModel.students.collectLatestOnStarted(viewLifecycleOwner) {
studentAdapter.submitData(it)
}
return binding.root
}
</code>
<code>override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { binding = DataBindingUtil.inflate(inflater, R.layout.fragment_first, container, false) studentAdapter = getStudentAdapter() binding.viewModel = viewModel binding.lifecycleOwner = viewLifecycleOwner setupOptionsMenu() binding.recyclerView.adapter = studentAdapter viewModel.students.collectLatestOnStarted(viewLifecycleOwner) { studentAdapter.submitData(it) } return binding.root } </code>
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
    binding = DataBindingUtil.inflate(inflater, R.layout.fragment_first, container, false)
    studentAdapter = getStudentAdapter()

    binding.viewModel = viewModel
    binding.lifecycleOwner = viewLifecycleOwner

    setupOptionsMenu()

    binding.recyclerView.adapter = studentAdapter

    viewModel.students.collectLatestOnStarted(viewLifecycleOwner) {
        studentAdapter.submitData(it)
    }

    return binding.root
}

Now the paging feature works fine, it loads and shows the last page at startup but not scrolling to the bottom, same as when new data is added.

So how can I make it scoll to bottom at startup and auto-scroll-to-bottom when new data is added?

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật