Android Room Paging — Complete Guide
In this tutorial, you'll learn about Android Room Paging. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
The Problem
You load 10,000 records at once, the UI freezes, and OutOfMemoryError crashes your app. You try manual pagination but get duplicate items or gaps.
Wrong Approach ❌
@Dao
interface UserDao {
@Query("SELECT * FROM users") // Loads ALL users at once
suspend fun getAllUsers(): List<User>
}
// Manual LIMIT/OFFSET without position tracking
@Query("SELECT * FROM users LIMIT :limit OFFSET :offset")
suspend fun getPage(limit: Int, offset: Int): List<User>
Output: UI thread blocked, OutOfMemoryError with large datasets. Pagination gaps when items are inserted/deleted.
Right Approach ✅
@Dao
interface UserDao {
@Query("SELECT * FROM users ORDER BY id ASC")
fun getPagedUsers(): PagingSource<Int, User>
}
// In ViewModel
class UserViewModel(userDao: UserDao) : ViewModel() {
val pager = Pager(PagingConfig(pageSize = 50)) {
userDao.getPagedUsers()
}.flow.cachedIn(viewModelScope)
// Or for remote + local:
val remotePager = Pager(PagingConfig(pageSize = 30)) {
RemoteMediatorRemoteKeys(...) // RemoteMediator for network paging
}.flow
}
// Composable usage
val users = pager.collectAsLazyPagingItems()
LazyColumn {
items(users) { user ->
if (user != null) {
UserRow(user)
}
}
}
Output: Memory-efficient Lazy Loading with Infinite Scroll.
Prevention
- Use
PagingSourcefor database queries — neverLIMIT/OFFSETmanually. - Use
RemoteMediatorfor network + database paging. - Configure
PagingConfigwith appropriatepageSize(20-50). - Use
cachedIn(viewModelScope)to avoid re-fetching on config changes.
Common Mistakes with room paging
- Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
These mistakes appear frequently in real-world Android code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro