I am currently building a Flickr-like app and I do have a question about pagination.
I am currently calling a FlickrApi to retrieve the recent photos. It's working well but I only get the first 100 because the api only returned list of photos using page
so it avoid to have 10000 photos in one call.
The JSON returned look like this:
{
"photos": {
"page": 1,
"pages": 10,
"perpage": 100,
"total": 1000,
"photo": [...]
My repository to call the api look like this:
override suspend fun getRecentPhotos(): FlickrResult<FlickrPhotosList?> = withContext(Dispatchers.IO) {
when (val response = flickrApiHelper.getRecentPhotos()) {
is FlickrApiResult.OnSuccess -> {
FlickrResult.OnSuccess(
FlickrMapper.fromRetrofitToFlickrPhotosList(response.data)
)
}
is FlickrApiResult.OnError -> {
FlickrResult.OnError(
response.exception
)
}
}
}
and the interface is :
interface FlickrApiHelper {
suspend fun getRecentPhotos(page: Int = 1): FlickrApiResult<RetrofitPhotosItem>
}
the viewModel is done like below:
fun getRecentPhotos() {
viewModelScope.launch {
_flickerPhotoState.value = FlickrState.Loading
withContext(Dispatchers.IO) {
when(val result = flickrUseCases.getRecentPhotos()) {
is FlickrResult.OnSuccess -> {
result.data?.photo?.let {
if(it.isNotEmpty()) {
_flickerPhotoState.value = FlickrState.DisplayPhotos(
Mapper.fromListFlickrPhotoItemToListPhotoDetails(it)
)
} else {
_flickerPhotoState.value = FlickrState.NoPhotos
}
return@withContext
}
_flickerPhotoState.value = FlickrState.NoPhotos
}
is FlickrResult.OnError -> {
_flickerPhotoState.value = FlickrState.Error(result.exception)
}
}
}
}
}
What I am trying to achieve to add a loop and place successive call to get page 2, 3....
I cannot figure-out a good way to plug the loop. My goal is really to place a call, update UI through state flow, place a call to next page, add to UI..
I would prefer to do it in the repository rather than the viewModel, but I am not sure what is the best place.
Any idea ?