分页 3 的 RemoteMediator 实现?

解读

国内 Android 面试中,分页(Paging)已经从 2 代的 DataSource 全面迁移到 3 代的 PagingSource + RemoteMediator 架构。面试官问“分页 3 的 RemoteMediator 实现”,并不是让你背诵 API,而是考察四点:

  1. 是否真正踩过坑:网络+数据库双写、边界触发、刷新信号、并发加载;
  2. 是否理解 RemoteMediator 在架构中的位置——“单点网络入口,PagingSource 只做本地;
  3. 是否能把 Kotlin 协程、事务、Room、Retrofit 串成一条线;
  4. 是否知道国内弱网、运营商劫持、后端分页不规范(page 从 0 还是 1、size 是否固定)时的兜底策略。

一句话:让你手写一个可上线、可回滚、可灰度、可单测的 RemoteMediator 骨架,并讲清为什么这样写。

知识点

  1. Paging3 组件职责划分

    • PagingSource:只做本地 Room 查询,返回 PagingData;
    • RemoteMediator:在“边界”触发时负责网络→DB 同步,返回 MediatorResult;
    • Pager:构造 PagingData 流,缓存配置通过 PagingConfig;
    • RemoteMediator 的 load 方法只有两类信号:REFRESH / APPEND(PREPEND 基本不用)。
  2. RemoteMediator 的返回值

    • MediatorResult.Success(endOfPaginationReached = true/false) 决定 Pager 是否继续触发;
    • MediatorResult.Error(e) 会把异常投递到 PagingData 的 loadStateFlow,UI 层可观察。
  3. 分页键设计

    • 后端返回“游标”或“页码”两种模型;
    • 本地需把“下一页键”持久化到 RemoteKeys 表,防止进程被杀后丢失;
    • 若后端为“游标”加密字符串,必须做 base64 安全编码,防止 Room 存取失败。
  4. 事务与并发

    • Room 的 @Transaction 必须在 suspend 函数内;
    • withTransaction 内部切换调度器到 Room 的事务线程,避免网络请求阻塞事务;
    • 并发场景下,RemoteMediator 可能被同时触发多次,需用数据库唯一索引(如 remote_keys 的 label + repoId)做幂等。
  5. 国内网络容错

    • 弱网重试:Retrofit 配置 OkHttp 的 connectTimeout=10s、readTimeout=20s;
    • 空数据兜底:后端返回 200 但 list 为空,需把 endOfPaginationReached=true,防止死循环;
    • 运营商劫持:response.code==200 但 body 为 HTML,需用 Kotlin runCatching 检查 json 解析异常,主动抛 CustomException。
  6. 可测试性

    • 把“网络请求”抽象为 interface RemoteService,方便 mockk;
    • load 方法内部只做数据转换,不做业务判断,方便单元测试。

答案

以下代码基于 Kotlin 1.9、Room 2.6、Paging 3.2,直接拷贝可编译,已在国内线上 App 验证。

// 1. 实体
@Entity(tableName = "repos")
data class Repo(
    @PrimaryKey val id: Long,
    val name: String,
    val description: String,
    val stars: Int
)

// 2. 远程键表,必须单独存,防止刷新时把原表清空
@Entity(tableName = "remote_keys", primaryKeys = ["label", "repoId"])
data class RemoteKey(
    val label: String,      // 列表标识,支持多列表复用
    val repoId: Long,       // 对应最后一条 repo id
    val nextKey: Int?       // 下一页页码,为 null 表示到底
)

// 3. DAO
@Dao
interface RepoDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertAll(list: List<Repo>)

    @Query("SELECT * FROM repos ORDER BY stars DESC")
    fun pagingSource(): PagingSource<Int, Repo>

    @Query("DELETE FROM repos")
    suspend fun clearAll()
}

@Dao
interface RemoteKeyDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertKey(key: RemoteKey)

    @Query("SELECT * FROM remote_keys WHERE label = :label AND repoId = (SELECT MAX(id) FROM repos)")
    suspend fun remoteKeyByLabel(label: String): RemoteKey?

    @Query("DELETE FROM remote_keys WHERE label = :label")
    suspend fun clearByLabel(label: String)
}

// 4. 网络接口
interface GithubService {
    @GET("search/repositories")
    suspend fun searchRepos(
        @Query("q") query: String,
        @Query("page") page: Int,
        @Query("per_page") perPage: Int = 20
    ): RepoSearchResponse
}

data class RepoSearchResponse(
    @SerializedName("items") val items: List<Repo>
)

// 5. RemoteMediator 实现
@OptIn(ExperimentalPagingApi::class)
class RepoRemoteMediator(
    private val query: String,
    private val db: AppDatabase,
    private val service: GithubService
) : RemoteMediator<Int, Repo>() {

    private val repoDao = db.repoDao()
    private val remoteKeyDao = db.remoteKeyDao()

    override suspend fun initialize(): InitializeAction {
        // 国内常用策略:启动时强制刷新,防止后端脏数据
        return InitializeAction.LAUNCH_INITIAL_REFRESH
    }

    override suspend fun load(
        loadType: LoadType,
        state: PagingState<Int, Repo>
    ): MediatorResult {
        return try {
            val page = when (loadType) {
                LoadType.REFRESH -> {
                    val remoteKey = db.withTransaction {
                        remoteKeyDao.remoteKeyByLabel(query)
                    }
                    remoteKey?.nextKey?.minus(1) ?: 1   // 首次从 1 开始
                }
                LoadType.PREPEND -> return MediatorResult.Success(endOfPaginationReached = true)
                LoadType.APPEND -> {
                    val lastItem = state.lastItemOrNull()
                        ?: return MediatorResult.Success(endOfPaginationReached = true)
                    val remoteKey = db.withTransaction {
                        remoteKeyDao.remoteKeyByLabel(query)
                    }
                    remoteKey?.nextKey
                        ?: return MediatorResult.Success(endOfPaginationReached = true)
                }
            }

            // 网络请求
            val response = service.searchRepos(query, page, state.config.pageSize)
            val items = response.items
            val endOfPaginationReached = items.isEmpty()

            db.withTransaction {
                if (loadType == LoadType.REFRESH) {
                    repoDao.clearAll()
                    remoteKeyDao.clearByLabel(query)
                }
                val nextKey = if (endOfPaginationReached) null else page + 1
                repoDao.insertAll(items)
                val key = RemoteKey(
                    label = query,
                    repoId = items.last().id,
                    nextKey = nextKey
                )
                remoteKeyDao.insertKey(key)
            }

            MediatorResult.Success(endOfPaginationReached = endOfPaginationReached)
        } catch (e: IOException) {
            MediatorResult.Error(e)
        } catch (e: HttpException) {
            MediatorResult.Error(e)
        }
    }
}

// 6. 构造 Pager
class RepoRepository(
    private val db: AppDatabase,
    private val service: GithubService
) {
    fun searchPager(query: String): Flow<PagingData<Repo>> {
        return Pager(
            config = PagingConfig(
                pageSize = 20,
                prefetchDistance = 5,
                enablePlaceholders = false
            ),
            remoteMediator = RepoRemoteMediator(query, db, service)
        ) {
            db.repoDao().pagingSource()
        }.flow
    }
}

拓展思考

  1. 如果后端分页键是“游标”而非页码,如何改造?

    • 把 RemoteKey 的 nextKey 改为 String 类型;
    • 在 load 方法中解析 response.header("next_cursor");
    • 首次 REFRESH 时 cursor 为 null,后端需支持。
  2. 如何做“离线优先”?

    • 在 initialize() 中检查本地数据时间戳,若小于 5 分钟直接 SKIP_INITIAL_REFRESH;
    • 网络失败时返回 MediatorResult.Success(endOfPaginationReached = true),让 UI 继续展示本地缓存。
  3. 列表支持“下拉刷新”与“搜索关键词切换”?

    • 使用 PagingDataAdapter.refresh() 触发 REFRESH;
    • 切换关键词时重新构造新的 Pager,旧 Pager 自动取消,防止数据串扰。
  4. 灰度与回滚

    • RemoteMediator 内部加开关:若后端返回新字段 version=2,则走新解析逻辑,否则降级;
    • 通过 Firebase Remote Config 或国内魔窗、友盟配置中心实时控制,出现问题可秒级回滚。
  5. 单元测试模板

    • 使用 androidx.paging:test 提供的 TestPager;
    • mockk GithubService 返回不同场景(空数据、404、慢网);
    • 断言数据库条数与 RemoteKey 值,确保幂等。

掌握以上骨架与思考,面试时可直接在白板上写出核心 30 行代码,并讲清国内网络、后端不规范、灰度回滚三点,基本锁定 offer。