Search code examples
androidkotlinandroid-jetpackandroid-paging-3

How to map PagingSource to another object


I implement paging 3 follow this codelab. codelab But when i create UserPagingRepository, i have problem that data class is not map. In Room DataBase, i use UserLocal otherhand i use UserRemote for data get from api. How can I convert data from data layer to domain layer (class User).

const val NETWORK_PAGE_SIZE = 20

class UserPagingRepository(
    private val service: UserApiService,
    private val database: UserDatabase
) {
    fun getUsersPaging(): Flow<PagingData<User>> {
        val pagingSourceFactory = { database.usersDao().getPagingUsers() }
        return Pager(
            config = PagingConfig(
                pageSize = NETWORK_PAGE_SIZE,
                enablePlaceholders = false
            ),
            pagingSourceFactory = pagingSourceFactory,
            remoteMediator = UserRemoteMediator(service, database)
        )
    }
}

fix:

pager.flow // Type is Flow<PagingData<User>>.
  .map { pagingData ->
    pagingData.map { user -> UiModel(user) }
  }

Solution

  • In flow downstream like in ViewModel, when you call for paging data apply map before collecting.

    searchRepo.searchUser(it)
       .map { user ->
          UserData.asDomainLayer()
       }
       .cachedIn(viewModelScope)