A
A
arteskin2021-12-04 20:09:34
Android
arteskin, 2021-12-04 20:09:34

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)
        }
    }
}


Then there is a repository which returns PagingData
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
}


And there is a UseCase which calls the repository method
class GetMovies(
    private val repository: MovieRepository
) {
    operator fun invoke() = Movies(
        popular = repository.getMovies("popular")
    )
}


As far as I understand, passing the query parameter in the user case violates the clean architecture, since different APIs have their own requests, and this should not be done in the domain layer. How to avoid it? I see the option of creating many methods in the repository for each query, but this is hardly what you need

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
Jacen11, 2021-12-05
@Jacen11

violates the clean architecture, since different APIs have their own requests
how are your requests and clean architecture related?
and this should not be done in the domain layer
what should not be done? parameter passing? what the fuck

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question