From c8e4c59b7e0c80f2b7b87e07f5963f2002029e40 Mon Sep 17 00:00:00 2001 From: Orestis Gartaganis Date: Mon, 31 Jan 2022 19:01:46 +0200 Subject: [PATCH] Fixed some logical errors; - lastRequested page incrementation is skipped if not going through the "Request more" so added to the requestAndSaveData instead as it was leading to erroneous counting - Requesting was endless even though the results might have been finite. Fixed by keeping the totalItemCount from the response and adding it to the condition of either to request more or not. --- .../codelabs/paging/data/GithubRepository.kt | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/com/example/android/codelabs/paging/data/GithubRepository.kt b/app/src/main/java/com/example/android/codelabs/paging/data/GithubRepository.kt index 010d1007..a552dc96 100644 --- a/app/src/main/java/com/example/android/codelabs/paging/data/GithubRepository.kt +++ b/app/src/main/java/com/example/android/codelabs/paging/data/GithubRepository.kt @@ -44,6 +44,10 @@ class GithubRepository(private val service: GithubService) { // keep the last requested page. When the request is successful, increment the page number. private var lastRequestedPage = GITHUB_STARTING_PAGE_INDEX + // keeps the total number of available items from our service, necessary to + // go through with requesting more or not + private var totalItemCount = Int.MAX_VALUE + // avoid triggering multiple requests in the same time private var isRequestInProgress = false @@ -54,6 +58,7 @@ class GithubRepository(private val service: GithubService) { suspend fun getSearchResultStream(query: String): Flow { Log.d("GithubRepository", "New query: $query") lastRequestedPage = 1 + totalItemCount = Int.MAX_VALUE inMemoryCache.clear() requestAndSaveData(query) @@ -62,10 +67,8 @@ class GithubRepository(private val service: GithubService) { suspend fun requestMore(query: String) { if (isRequestInProgress) return - val successful = requestAndSaveData(query) - if (successful) { - lastRequestedPage++ - } + if (totalItemCount < (lastRequestedPage - 1) * NETWORK_PAGE_SIZE) return + requestAndSaveData(query) } suspend fun retry(query: String) { @@ -82,9 +85,11 @@ class GithubRepository(private val service: GithubService) { val response = service.searchRepos(apiQuery, lastRequestedPage, NETWORK_PAGE_SIZE) Log.d("GithubRepository", "response $response") val repos = response.items ?: emptyList() + totalItemCount = response.total inMemoryCache.addAll(repos) val reposByName = reposByName(query) searchResults.emit(RepoSearchResult.Success(reposByName)) + lastRequestedPage++ successful = true } catch (exception: IOException) { searchResults.emit(RepoSearchResult.Error(exception))