'Android Paging 3 with Repository pattern?
Just doing some self-study on the Android Pagination 3 library.
I'm a bit confused as to how PageSource and Pager fit with the current Repository pattern.
So in the diagram, it says that PageSource should be inside the Repository layer and Pager should be in the ViewModel layer.
Does this mean that my Repository should extend PageSource? Or does this mean my ViewModel should be injected with multiple Repositories?
What is the standard way of doing this?
Solution 1:[1]
This is how i do this scenario: 1-Return value of functions in dao is PagingSource<----,---->
@RawQuery(observedEntities = [CoinEntity::class])
fun getAllCoinsWithPaging(query: SupportSQLiteQuery): PagingSource<Int, CoinEntity>
2-Call a function in repository which create a Pager using RemoteMediator and Dao's functions.
@OptIn(ExperimentalPagingApi::class)
override fun getCoinByPage(pageSize: Int) = Pager(
config = PagingConfig(pageSize),
remoteMediator = coinRemoteMediator
) {
val myQuery =
SimpleSQLiteQuery("SELECT * FROM coin_entity")
db.coinDao().getAllCoinsWithPaging(myQuery)
}.flow.mapLatest { pagingData ->
pagingData.map { entity ->
entity.toCoinDomainModel()
}
}
3-Now in viewModel or UseCase i just call that repository's function (which create Pager ).
class GetCoinsWithPagingUseCase @Inject constructor
(
private val coinRepository: CoinPagingRepository,
) :
UseCase<Int, Flow<PagingData<CoinDomainModel>>>() {
override fun execute(parameters: Int): Flow<PagingData<CoinDomainModel>> {
return coinRepository.getCoinByPage(parameters)
}
}
@HiltViewModel
class HomeViewModel @Inject constructor(
private val getCoinsWithPagingUseCase: GetCoinsWithPagingUseCase
) : BaseViewModel() {
lateinit var coins: Flow<PagingData<CoinDomainModel>>
init {
AppConstant.sortType = SortType.ASC
initFlow()
}
fun initFlow() {
coins = getCoinsWithPagingUseCase(20).cachedIn(viewModelScope)
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
