如何将Room的PagingSource<Int, ItemRoomEntity>映射为领域层对应类型?
如何将Room返回的PagingSource<Int, ItemRoomEntity>映射为领域层的PagingSource<Int, ItemEntity>
你可以利用Jetpack Paging库为PagingSource提供的map扩展函数,直接将数据层的ItemRoomEntity转换为领域层的ItemEntity,同时保留分页的核心逻辑。
直接修改Repository实现
修改ItemRepositoryImpl中的getItemsPaged方法,通过map操作完成类型转换:
import androidx.paging.map class ItemRepositoryImpl( private val itemDao: ItemDao ) : ItemRepository { override fun getItemsPaged(): PagingSource<Int, ItemEntity> = itemDao.getPaging().map { roomEntity -> ItemEntity(id = roomEntity.id, name = roomEntity.name) } }
优化映射逻辑(可选)
如果后续实体字段增多或映射逻辑变复杂,建议将映射逻辑抽离,保证代码的可维护性:
方式1:使用扩展函数
在数据层定义扩展函数,专门负责实体转换:
// 数据层的扩展函数 fun ItemRoomEntity.toDomainEntity(): ItemEntity { return ItemEntity(id = this.id, name = this.name) }
然后在Repository中调用:
class ItemRepositoryImpl( private val itemDao: ItemDao ) : ItemRepository { override fun getItemsPaged(): PagingSource<Int, ItemEntity> = itemDao.getPaging().map { it.toDomainEntity() } }
方式2:使用映射器类
对于更复杂的映射场景,创建专门的映射器类,符合单一职责原则:
class ItemRoomToDomainMapper { fun map(roomEntity: ItemRoomEntity): ItemEntity { return ItemEntity(roomEntity.id, roomEntity.name) } }
在Repository中注入并使用该映射器:
class ItemRepositoryImpl( private val itemDao: ItemDao, private val mapper: ItemRoomToDomainMapper ) : ItemRepository { override fun getItemsPaged(): PagingSource<Int, ItemEntity> = itemDao.getPaging().map { mapper.map(it) } }
关键说明
PagingSource.map是懒执行的:只有当数据被实际加载(比如列表滚动到对应分页)时,才会进行实体转换,不会提前消耗内存处理所有数据。- 确保导入正确的扩展函数包:
import androidx.paging.map,否则无法调用map方法。
内容的提问来源于stack exchange,提问作者Artem Krylov
相关产品推荐
相关产品推荐

