Answer the question
In order to leave comments, you need to log in
How to use Paging3 with clean architecture?
There is a PagingSource that, depending on the query parameter, receives different data from the API.
class MoviePagingSource(
private val service: MovieService,
private val query: String
) : PagingSource<Int, Movie>() {
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Movie> {
val page = params.key ?: 1
val response = service.getMovies(query, page)
return try {
val movies = response.result.map { it.toMovie() }
val prevKey = if (page != 0) page - 1 else null
val nextKey = if (page < response.total_pages) page + 1 else null
LoadResult.Page(movies, prevKey, nextKey)
} catch (e: Exception) {
LoadResult.Error(e)
}
}
}
class MovieRepositoryImpl(
private val service: MovieService
): MovieRepository {
override fun getMovies(query: String): Flow<PagingData<Movie>> =
Pager(
config = PagingConfig(pageSize = 20),
pagingSourceFactory = { MoviePagingSource(service, query) }
).flow
}
class GetMovies(
private val repository: MovieRepository
) {
operator fun invoke() = Movies(
popular = repository.getMovies("popular")
)
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question