diff --git a/app/build.gradle b/app/build.gradle index 8d7d5419..a2f57917 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -62,8 +62,9 @@ dependencies { implementation "com.google.android.material:material:$materialVersion" // architecture components + implementation "androidx.core:core-ktx:$coreVersion" implementation "androidx.lifecycle:lifecycle-extensions:$lifecycleVersion" - implementation "androidx.lifecycle:lifecycle-runtime:$lifecycleVersion" + implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycleVersion" implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycleVersion" implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycleVersion" implementation "androidx.room:room-runtime:$roomVersion" diff --git a/app/src/main/java/com/example/android/codelabs/paging/data/GithubPagingSource.kt b/app/src/main/java/com/example/android/codelabs/paging/data/GithubPagingSource.kt new file mode 100644 index 00000000..5e7dda97 --- /dev/null +++ b/app/src/main/java/com/example/android/codelabs/paging/data/GithubPagingSource.kt @@ -0,0 +1,50 @@ +/* + * 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 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 + +class GithubPagingSource( + private val service: GithubService, + private val query: String +) : PagingSource() { + override suspend fun load(params: LoadParams): LoadResult { + val position = params.key ?: GITHUB_STARTING_PAGE_INDEX + val apiQuery = query + IN_QUALIFIER + return try { + val response = service.searchRepos(apiQuery, position, params.loadSize) + val repos = response.items + LoadResult.Page( + data = repos, + prevKey = if (position == GITHUB_STARTING_PAGE_INDEX) null else position - 1, + nextKey = if (repos.isEmpty()) null else position + 1 + ) + } catch (exception: IOException) { + LoadResult.Error(exception) + } catch (exception: HttpException) { + LoadResult.Error(exception) + } + } +} 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 77000d4f..1b18eb34 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 @@ -17,95 +17,28 @@ package com.example.android.codelabs.paging.data import android.util.Log +import androidx.paging.Pager +import androidx.paging.PagingConfig +import androidx.paging.PagingData 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() - - // keep channel of results. The channel allows us to broadcast updates so - // the subscriber will have the latest data - private val searchResults = ConflatedBroadcastChannel() - - // 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 { + fun getSearchResultStream(query: String): Flow> { Log.d("GithubRepository", "New query: $query") - lastRequestedPage = 1 - inMemoryCache.clear() - 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") - val repos = response.items ?: emptyList() - inMemoryCache.addAll(repos) - val reposByName = reposByName(query) - searchResults.offer(RepoSearchResult.Success(reposByName)) - successful = true - } 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 { - // 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 { it.stars }.thenBy { it.name }) + return Pager( + config = PagingConfig(pageSize = NETWORK_PAGE_SIZE), + pagingSourceFactory = { GithubPagingSource(service, query) } + ).flow } companion object { diff --git a/app/src/main/java/com/example/android/codelabs/paging/ui/ReposAdapter.kt b/app/src/main/java/com/example/android/codelabs/paging/ui/ReposAdapter.kt index d959d265..3a5a4e73 100644 --- a/app/src/main/java/com/example/android/codelabs/paging/ui/ReposAdapter.kt +++ b/app/src/main/java/com/example/android/codelabs/paging/ui/ReposAdapter.kt @@ -17,20 +17,21 @@ 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.model.Repo /** * Adapter for the list of repositories. */ -class ReposAdapter : ListAdapter(REPO_COMPARATOR) { +class ReposAdapter : PagingDataAdapter(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) { + override fun onBindViewHolder(holder: ViewHolder, position: Int) { val repoItem = getItem(position) if (repoItem != null) { (holder as RepoViewHolder).bind(repoItem) diff --git a/app/src/main/java/com/example/android/codelabs/paging/ui/ReposLoadStateAdapter.kt b/app/src/main/java/com/example/android/codelabs/paging/ui/ReposLoadStateAdapter.kt new file mode 100644 index 00000000..1350bd66 --- /dev/null +++ b/app/src/main/java/com/example/android/codelabs/paging/ui/ReposLoadStateAdapter.kt @@ -0,0 +1,33 @@ +/* + * Copyright (C) 2020 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.ui + +import android.view.ViewGroup +import androidx.paging.LoadState +import androidx.paging.LoadStateAdapter + +class ReposLoadStateAdapter( + private val retry: () -> Unit +) : LoadStateAdapter() { + override fun onBindViewHolder(holder: ReposLoadStateViewHolder, loadState: LoadState) { + holder.bind(loadState) + } + + override fun onCreateViewHolder(parent: ViewGroup, loadState: LoadState): ReposLoadStateViewHolder { + return ReposLoadStateViewHolder.create(parent, retry) + } +} diff --git a/app/src/main/java/com/example/android/codelabs/paging/ui/ReposLoadStateViewHolder.kt b/app/src/main/java/com/example/android/codelabs/paging/ui/ReposLoadStateViewHolder.kt new file mode 100644 index 00000000..0a056d07 --- /dev/null +++ b/app/src/main/java/com/example/android/codelabs/paging/ui/ReposLoadStateViewHolder.kt @@ -0,0 +1,53 @@ +/* + * Copyright (C) 2020 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.ui + +import android.view.LayoutInflater +import android.view.ViewGroup +import androidx.core.view.isVisible +import androidx.paging.LoadState +import androidx.recyclerview.widget.RecyclerView +import com.example.android.codelabs.paging.R +import com.example.android.codelabs.paging.databinding.ReposLoadStateFooterViewItemBinding + +class ReposLoadStateViewHolder( + private val binding: ReposLoadStateFooterViewItemBinding, + retry: () -> Unit +) : RecyclerView.ViewHolder(binding.root) { + + init { + binding.retryButton.setOnClickListener { retry.invoke() } + } + + fun bind(loadState: LoadState) { + if (loadState is LoadState.Error) { + binding.errorMsg.text = loadState.error.localizedMessage + } + binding.progressBar.isVisible = loadState is LoadState.Loading + binding.retryButton.isVisible = loadState !is LoadState.Loading + binding.errorMsg.isVisible = loadState !is LoadState.Loading + } + + companion object { + fun create(parent: ViewGroup, retry: () -> Unit): ReposLoadStateViewHolder { + val view = LayoutInflater.from(parent.context) + .inflate(R.layout.repos_load_state_footer_view_item, parent, false) + val binding = ReposLoadStateFooterViewItemBinding.bind(view) + return ReposLoadStateViewHolder(binding, retry) + } + } +} diff --git a/app/src/main/java/com/example/android/codelabs/paging/ui/SearchRepositoriesActivity.kt b/app/src/main/java/com/example/android/codelabs/paging/ui/SearchRepositoriesActivity.kt index 64cad7ae..ff2596dc 100644 --- a/app/src/main/java/com/example/android/codelabs/paging/ui/SearchRepositoriesActivity.kt +++ b/app/src/main/java/com/example/android/codelabs/paging/ui/SearchRepositoriesActivity.kt @@ -22,16 +22,19 @@ import android.view.View import android.view.inputmethod.EditorInfo import android.widget.Toast import androidx.appcompat.app.AppCompatActivity +import androidx.core.view.isVisible import androidx.lifecycle.ViewModelProvider -import androidx.lifecycle.observe +import androidx.lifecycle.lifecycleScope +import androidx.paging.ExperimentalPagingApi +import androidx.paging.LoadState import androidx.recyclerview.widget.DividerItemDecoration -import androidx.recyclerview.widget.LinearLayoutManager -import androidx.recyclerview.widget.RecyclerView -import androidx.recyclerview.widget.RecyclerView.OnScrollListener import com.example.android.codelabs.paging.Injection import com.example.android.codelabs.paging.databinding.ActivitySearchRepositoriesBinding -import com.example.android.codelabs.paging.model.RepoSearchResult import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.collect +import kotlinx.coroutines.flow.collectLatest +import kotlinx.coroutines.launch @ExperimentalCoroutinesApi class SearchRepositoriesActivity : AppCompatActivity() { @@ -40,6 +43,18 @@ class SearchRepositoriesActivity : AppCompatActivity() { private lateinit var viewModel: SearchRepositoriesViewModel private val adapter = ReposAdapter() + private var searchJob: Job? = null + + private fun search(query: String) { + // Make sure we cancel the previous job before creating a new one + searchJob?.cancel() + searchJob = lifecycleScope.launch { + viewModel.searchRepo(query).collectLatest { + adapter.submitData(it) + } + } + } + override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivitySearchRepositoriesBinding.inflate(layoutInflater) @@ -53,14 +68,12 @@ class SearchRepositoriesActivity : AppCompatActivity() { // add dividers between RecyclerView's row items val decoration = DividerItemDecoration(this, DividerItemDecoration.VERTICAL) binding.list.addItemDecoration(decoration) - setupScrollListener() initAdapter() val query = savedInstanceState?.getString(LAST_SEARCH_QUERY) ?: DEFAULT_QUERY - if (viewModel.repoResult.value == null) { - viewModel.searchRepo(query) - } + search(query) initSearch(query) + binding.retryButton.setOnClickListener { adapter.retry() } } override fun onSaveInstanceState(outState: Bundle) { @@ -69,20 +82,29 @@ class SearchRepositoriesActivity : AppCompatActivity() { } private fun initAdapter() { - binding.list.adapter = adapter - viewModel.repoResult.observe(this) { result -> - when (result) { - is RepoSearchResult.Success -> { - showEmptyList(result.data.isEmpty()) - adapter.submitList(result.data) - } - is RepoSearchResult.Error -> { - Toast.makeText( - this, - "\uD83D\uDE28 Wooops $result.message}", - Toast.LENGTH_LONG - ).show() - } + binding.list.adapter = adapter.withLoadStateHeaderAndFooter( + header = ReposLoadStateAdapter { adapter.retry() }, + footer = ReposLoadStateAdapter { adapter.retry() } + ) + adapter.addLoadStateListener { loadState -> + // Only show the list if refresh succeeds. + binding.list.isVisible = loadState.refresh is LoadState.NotLoading + // Show loading spinner during initial load or refresh. + binding.progressBar.isVisible = loadState.refresh is LoadState.Loading + // Show the retry state if initial load or refresh fails. + binding.retryButton.isVisible = loadState.refresh is LoadState.Error + + // Toast on any error, regardless of whether it came from RemoteMediator or PagingSource + val errorState = loadState.source.append as? LoadState.Error + ?: loadState.source.prepend as? LoadState.Error + ?: loadState.append as? LoadState.Error + ?: loadState.prepend as? LoadState.Error + errorState?.let { + Toast.makeText( + this, + "\uD83D\uDE28 Wooops ${it.error}", + Toast.LENGTH_LONG + ).show() } } } @@ -106,39 +128,21 @@ class SearchRepositoriesActivity : AppCompatActivity() { false } } - } - private fun updateRepoListFromInput() { - binding.searchRepo.text.trim().let { - if (it.isNotEmpty()) { + lifecycleScope.launch { + @OptIn(ExperimentalPagingApi::class) + adapter.dataRefreshFlow.collect { binding.list.scrollToPosition(0) - viewModel.searchRepo(it.toString()) } } } - private fun showEmptyList(show: Boolean) { - if (show) { - binding.emptyList.visibility = View.VISIBLE - binding.list.visibility = View.GONE - } else { - binding.emptyList.visibility = View.GONE - binding.list.visibility = View.VISIBLE - } - } - - private fun setupScrollListener() { - val layoutManager = binding.list.layoutManager as LinearLayoutManager - binding.list.addOnScrollListener(object : OnScrollListener() { - override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { - super.onScrolled(recyclerView, dx, dy) - val totalItemCount = layoutManager.itemCount - val visibleItemCount = layoutManager.childCount - val lastVisibleItem = layoutManager.findLastVisibleItemPosition() - - viewModel.listScrolled(visibleItemCount, lastVisibleItem, totalItemCount) + private fun updateRepoListFromInput() { + binding.searchRepo.text.trim().let { + if (it.isNotEmpty()) { + search(it.toString()) } - }) + } } companion object { diff --git a/app/src/main/java/com/example/android/codelabs/paging/ui/SearchRepositoriesViewModel.kt b/app/src/main/java/com/example/android/codelabs/paging/ui/SearchRepositoriesViewModel.kt index e7748559..25aa0026 100644 --- a/app/src/main/java/com/example/android/codelabs/paging/ui/SearchRepositoriesViewModel.kt +++ b/app/src/main/java/com/example/android/codelabs/paging/ui/SearchRepositoriesViewModel.kt @@ -16,13 +16,14 @@ package com.example.android.codelabs.paging.ui -import androidx.lifecycle.* +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import androidx.paging.PagingData +import androidx.paging.cachedIn import com.example.android.codelabs.paging.data.GithubRepository -import com.example.android.codelabs.paging.model.RepoSearchResult -import kotlinx.coroutines.Dispatchers +import com.example.android.codelabs.paging.model.Repo import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.FlowPreview -import kotlinx.coroutines.launch +import kotlinx.coroutines.flow.Flow /** * ViewModel for the [SearchRepositoriesActivity] screen. @@ -30,34 +31,19 @@ import kotlinx.coroutines.launch */ @ExperimentalCoroutinesApi class SearchRepositoriesViewModel(private val repository: GithubRepository) : ViewModel() { + private var currentQueryValue: String? = null - companion object { - private const val VISIBLE_THRESHOLD = 5 - } - - private val queryLiveData = MutableLiveData() - val repoResult: LiveData = queryLiveData.switchMap { queryString -> - liveData { - val repos = repository.getSearchResultStream(queryString).asLiveData(Dispatchers.Main) - emitSource(repos) - } - } - - /** - * Search a repository based on a query string. - */ - fun searchRepo(queryString: String) { - queryLiveData.postValue(queryString) - } + private var currentSearchResult: Flow>? = null - fun listScrolled(visibleItemCount: Int, lastVisibleItemPosition: Int, totalItemCount: Int) { - if (visibleItemCount + lastVisibleItemPosition + VISIBLE_THRESHOLD >= totalItemCount) { - val immutableQuery = queryLiveData.value - if (immutableQuery != null) { - viewModelScope.launch { - repository.requestMore(immutableQuery) - } - } + fun searchRepo(queryString: String): Flow> { + val lastResult = currentSearchResult + if (queryString == currentQueryValue && lastResult != null) { + return lastResult } + currentQueryValue = queryString + val newResult: Flow> = repository.getSearchResultStream(queryString) + .cachedIn(viewModelScope) + currentSearchResult = newResult + return newResult } -} \ No newline at end of file +} diff --git a/app/src/main/java/com/example/android/codelabs/paging/ui/UiUtils.kt b/app/src/main/java/com/example/android/codelabs/paging/ui/UiUtils.kt deleted file mode 100644 index ddf003b1..00000000 --- a/app/src/main/java/com/example/android/codelabs/paging/ui/UiUtils.kt +++ /dev/null @@ -1,9 +0,0 @@ -package com.example.android.codelabs.paging.ui - -import android.view.View - -fun toVisibility(constraint: Boolean): Int = if (constraint) { - View.VISIBLE -} else { - View.GONE -} \ No newline at end of file diff --git a/app/src/main/res/layout/activity_search_repositories.xml b/app/src/main/res/layout/activity_search_repositories.xml index 738040a3..5695d150 100644 --- a/app/src/main/res/layout/activity_search_repositories.xml +++ b/app/src/main/res/layout/activity_search_repositories.xml @@ -59,16 +59,25 @@ app:layout_constraintTop_toBottomOf="@+id/input_layout" tools:ignore="UnusedAttribute"/> - + + +