Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.android.codelabs.paging.data

import androidx.paging.PagingSource
import com.example.android.codelabs.paging.api.GithubService
import com.example.android.codelabs.paging.api.IN_QUALIFIER
import com.example.android.codelabs.paging.model.Repo
import kotlinx.coroutines.ExperimentalCoroutinesApi
import retrofit2.HttpException
import java.io.IOException

// GitHub page API is 1 based: https://developer.github.com/v3/#pagination
private const val GITHUB_STARTING_PAGE_INDEX = 1

@ExperimentalCoroutinesApi
class GithubPagingSource(
private val service: GithubService,
private val query: String
) : PagingSource<Int, Repo>() {
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Repo> {
val currentPage = params.key ?: GITHUB_STARTING_PAGE_INDEX
val apiQuery = query + IN_QUALIFIER
try {
val apiResponse = service.searchRepos(apiQuery, currentPage, params.loadSize)
return if (apiResponse.isSuccessful) {
val repos = apiResponse.body()?.items ?: emptyList()
LoadResult.Page(
data = repos,
prevKey = if (currentPage == GITHUB_STARTING_PAGE_INDEX) null else currentPage - 1,
// if we don't get any results, we consider that we're at the last page
nextKey = if (repos.isEmpty()) null else currentPage + 1
)
} else {
LoadResult.Error(IOException(apiResponse.message()))
}
} catch (exception: IOException) {
return LoadResult.Error(exception)
} catch (exception: HttpException) {
return LoadResult.Error(exception)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,107 +17,31 @@
package com.example.android.codelabs.paging.data

import android.util.Log
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.PagingDataFlow
import com.example.android.codelabs.paging.api.GithubService
import com.example.android.codelabs.paging.api.IN_QUALIFIER
import com.example.android.codelabs.paging.model.Repo
import com.example.android.codelabs.paging.model.RepoSearchResult
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.channels.ConflatedBroadcastChannel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.asFlow
import retrofit2.HttpException
import java.io.IOException

// GitHub page API is 1 based: https://developer.github.com/v3/#pagination
private const val GITHUB_STARTING_PAGE_INDEX = 1

/**
* Repository class that works with local and remote data sources.
*/
@ExperimentalCoroutinesApi
class GithubRepository(private val service: GithubService) {

// keep the list of all results received
private val inMemoryCache = mutableListOf<Repo>()

// keep channel of results. The channel allows us to broadcast updates so
// the subscriber will have the latest data
private val searchResults = ConflatedBroadcastChannel<RepoSearchResult>()

// keep the last requested page. When the request is successful, increment the page number.
private var lastRequestedPage = GITHUB_STARTING_PAGE_INDEX

// avoid triggering multiple requests in the same time
private var isRequestInProgress = false

/**
* Search repositories whose names match the query, exposed as a stream of data that will emit
* every time we get more data from the network.
*/
suspend fun getSearchResultStream(query: String): Flow<RepoSearchResult> {
fun getSearchResultStream(query: String): Flow<PagingData<Repo>> {
Log.d("GithubRepository", "New query: $query")
lastRequestedPage = 1
requestAndSaveData(query)

return searchResults.asFlow()
}

suspend fun requestMore(query: String) {
if (isRequestInProgress) return
val successful = requestAndSaveData(query)
if (successful) {
lastRequestedPage++
}
}

suspend fun retry(query: String) {
if (isRequestInProgress) return
requestAndSaveData(query)
}

private suspend fun requestAndSaveData(query: String): Boolean {
isRequestInProgress = true
var successful = false

val apiQuery = query + IN_QUALIFIER
try {
val response = service.searchRepos(apiQuery, lastRequestedPage, NETWORK_PAGE_SIZE)
Log.d("GithubRepository", "response $response")
if (response.isSuccessful) {
if (response.isSuccessful) {
val repos = response.body()?.items ?: emptyList()
inMemoryCache.addAll(repos)
val reposByName = reposByName(query)
searchResults.offer(RepoSearchResult.Success(reposByName))
successful = true
} else {
Log.d("GithubRepository", "fail to get data")
searchResults.offer(RepoSearchResult.Error(IOException(response.message()
?: "Unknown error")))
}
} else {
Log.d("GithubRepository", "fail to get data")
searchResults.offer(RepoSearchResult.Error(IOException(response.message()
?: "Unknown error")))
}
} catch (exception: IOException) {
searchResults.offer(RepoSearchResult.Error(exception))
} catch (exception: HttpException) {
searchResults.offer(RepoSearchResult.Error(exception))
}

isRequestInProgress = false
return successful
}

private fun reposByName(query: String): List<Repo> {
// from the in memory cache select only the repos whose name or description matches
// the query. Then order the results.
return inMemoryCache.filter {
it.name.contains(query, true) ||
(it.description != null && it.description.contains(query, true))
}.sortedWith(compareByDescending<Repo> { it.stars }.thenBy { it.name })
return PagingDataFlow(
config = PagingConfig(pageSize = NETWORK_PAGE_SIZE),
pagingSourceFactory = { GithubPagingSource(service, query) }
)
}

companion object {
Expand Down

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -17,24 +17,24 @@
package com.example.android.codelabs.paging.ui

import android.view.ViewGroup
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.example.android.codelabs.paging.R
import com.example.android.codelabs.paging.model.Repo

/**
* Adapter for the list of repositories.
*/
class ReposAdapter : ListAdapter<Repo, androidx.recyclerview.widget.RecyclerView.ViewHolder>(REPO_COMPARATOR) {
class ReposAdapter : PagingDataAdapter<Repo, ViewHolder>(REPO_COMPARATOR) {

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): androidx.recyclerview.widget.RecyclerView.ViewHolder {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return RepoViewHolder.create(parent)
}

override fun onBindViewHolder(holder: androidx.recyclerview.widget.RecyclerView.ViewHolder, position: Int) {
val repoItem = getItem(position)
if (repoItem != null) {
(holder as RepoViewHolder).bind(repoItem)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val repo = getItem(position)
(holder as RepoViewHolder).bind(repo)
}

companion object {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,56 +13,18 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.android.codelabs.paging.ui

import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView

class ReposLoadStateAdapter(private val retry: () -> Unit) : RecyclerView.Adapter<ReposLoadStateViewHolder>() {

/**
* LoadState to present in the adapter.
*
* Changing this property will immediately notify the Adapter to change the item it's
* presenting.
*/
var loadState: LoadState = LoadState.Done
set(loadState) {
if (field != loadState) {
val displayOldItem = displayLoadStateAsItem(field)
val displayNewItem = displayLoadStateAsItem(loadState)

if (displayOldItem && !displayNewItem) {
notifyItemRemoved(0)
} else if (displayNewItem && !displayOldItem) {
notifyItemInserted(0)
} else if (displayOldItem && displayNewItem) {
notifyItemChanged(0)
}
field = loadState
}
}
import androidx.paging.LoadState
import androidx.paging.LoadStateAdapter

override fun onBindViewHolder(holder: ReposLoadStateViewHolder, position: Int) {
class ReposLoadStateAdapter(private val retry: () -> Unit) : LoadStateAdapter<ReposLoadStateViewHolder>() {
override fun onBindViewHolder(holder: ReposLoadStateViewHolder, loadState: LoadState) {
holder.bind(loadState)
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ReposLoadStateViewHolder {
override fun onCreateViewHolder(parent: ViewGroup, loadState: LoadState): ReposLoadStateViewHolder {
return ReposLoadStateViewHolder.create(parent, retry)
}

override fun getItemViewType(position: Int): Int = 0

override fun getItemCount(): Int = if (displayLoadStateAsItem(loadState)) 1 else 0

/**
* Returns true if the LoadState should be displayed as a list item when active.
*
* [LoadState.Loading] and [LoadState.Error] present as list items,
* [LoadState.Done] is not.
*/
private fun displayLoadStateAsItem(loadState: LoadState): Boolean {
return loadState is LoadState.Loading || loadState is LoadState.Error
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import android.view.ViewGroup
import android.widget.Button
import android.widget.ProgressBar
import android.widget.TextView
import androidx.paging.LoadState
import androidx.recyclerview.widget.RecyclerView
import com.example.android.codelabs.paging.R
import com.example.android.codelabs.paging.databinding.ReposLoadStateHeaderViewItemBinding
Expand Down Expand Up @@ -60,4 +61,4 @@ class ReposLoadStateViewHolder(
return ReposLoadStateViewHolder(binding, retry)
}
}
}
}
Loading