Room + Paging 完全指南 — PagingSource/RemoteMediator/离线缓存
发布: (2026年3月2日 GMT+8 13:12)
3 分钟阅读
原文: Dev.to
Source: Dev.to
本文可学习的内容
DAO
@Dao
interface ArticleDao {
@Query("SELECT * FROM articles ORDER BY createdAt DESC")
fun getArticlesPaging(): PagingSource
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertAll(articles: List)
@Query("DELETE FROM articles")
suspend fun clearAll()
}
RemoteMediator
@OptIn(ExperimentalPagingApi::class)
class ArticleRemoteMediator @Inject constructor(
private val api: ArticleApi,
private val db: AppDatabase
) : RemoteMediator() {
override suspend fun load(loadType: LoadType, state: PagingState): MediatorResult {
val page = when (loadType) {
LoadType.REFRESH -> 1
LoadType.PREPEND -> return MediatorResult.Success(endOfPaginationReached = true)
LoadType.APPEND -> {
val lastItem = state.lastItemOrNull()
?: return MediatorResult.Success(endOfPaginationReached = true)
lastItem.page + 1
}
}
return try {
val response = api.getArticles(page = page, pageSize = state.config.pageSize)
db.withTransaction {
if (loadType == LoadType.REFRESH) {
db.articleDao().clearAll()
}
db.articleDao().insertAll(response.map { it.copy(page = page) })
}
MediatorResult.Success(endOfPaginationReached = response.isEmpty())
} catch (e: Exception) {
MediatorResult.Error(e)
}
}
}
Repository
class ArticleRepository @Inject constructor(
private val db: AppDatabase,
private val remoteMediator: ArticleRemoteMediator
) {
@OptIn(ExperimentalPagingApi::class)
fun getArticles(): Flow> {
return Pager(
config = PagingConfig(pageSize = 20, prefetchDistance = 5),
remoteMediator = remoteMediator,
pagingSourceFactory = { db.articleDao().getArticlesPaging() }
).flow
}
}
ViewModel
@HiltViewModel
class ArticleViewModel @Inject constructor(
repository: ArticleRepository
) : ViewModel() {
val articles = repository.getArticles().cachedIn(viewModelScope)
}
Compose UI
@Composable
fun ArticleList(viewModel: ArticleViewModel = hiltViewModel()) {
val articles = viewModel.articles.collectAsLazyPagingItems()
LazyColumn {
items(articles.itemCount) { index ->
articles[index]?.let { article ->
ListItem(
headlineContent = { Text(article.title) },
supportingContent = { Text(article.summary) }
)
}
}
when (articles.loadState.append) {
is LoadState.Loading -> item {
CircularProgressIndicator(
Modifier
.fillMaxWidth()
.padding(16.dp)
)
}
is LoadState.Error -> item {
Text("読み込みエラー", Modifier.padding(16.dp))
}
else -> {}
}
}
}
组件与职责
| 组件 | 角色 |
|---|---|
| PagingSource | 按页获取数据 |
| RemoteMediator | API → DB 同步 |
| Pager | 生成 PagingData |
| collectAsLazyPagingItems | 与 Compose 集成 |
- Room DAO 直接返回 PagingSource
- 使用 RemoteMediator 将 API → 本地 DB 缓存
- 即使离线也能从 DB 显示
- 通过 cachedIn(viewModelScope) 防止在重新组合时重新获取
模板公开
发布了 8 种 Android 应用模板(支持 Paging)。
模板列表 → Gumroad
相关文章
- Paging3
- Room/Flow
- 离线优先
我在 Gumroad 上发布了 8 个 Android 应用模板(Room DB、Material3、MVVM)。
Browse templates → Gumroad