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..3d941400 --- /dev/null +++ b/app/src/main/java/com/example/android/codelabs/paging/data/GithubPagingSource.kt @@ -0,0 +1,52 @@ +/* + * 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 kotlinx.coroutines.FlowPreview +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 +@FlowPreview +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 + val apiResponse = service.searchRepos(apiQuery, position, GithubRepository.NETWORK_PAGE_SIZE) + return if (apiResponse.isSuccessful) { + val repos = apiResponse.body()?.items ?: emptyList() + LoadResult.Page( + data = repos, + prevKey = if (position == GITHUB_STARTING_PAGE_INDEX) null else -1, + // if we don't get any results, we consider that we're at the last page + nextKey = if (repos.isEmpty()) null else position + 1 + ) + } else { + LoadResult.Error(IOException(apiResponse.message())) + } + } +} 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 25e6d478..8d8183dd 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,19 +17,14 @@ 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 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. @@ -38,73 +33,20 @@ private const val GITHUB_STARTING_PAGE_INDEX = 1 @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 - requestAndSaveData(query) - - return searchResults.asFlow() - } - - suspend fun requestMore(query: String) { - requestAndSaveData(query) - } - - private suspend fun requestAndSaveData(query: String) { - if (isRequestInProgress) return - - isRequestInProgress = true - - val apiQuery = query + IN_QUALIFIER - 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)) - } 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"))) - } - lastRequestedPage++ - isRequestInProgress = false - } - 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 PagingDataFlow( + config = PagingConfig(pageSize = NETWORK_PAGE_SIZE), + pagingSourceFactory = { GithubPagingSource(service, query) } + ) } companion object { - private const val NETWORK_PAGE_SIZE = 50 + const val NETWORK_PAGE_SIZE = 50 } } diff --git a/app/src/main/java/com/example/android/codelabs/paging/model/RepoSearchResult.kt b/app/src/main/java/com/example/android/codelabs/paging/model/RepoSearchResult.kt deleted file mode 100644 index d00c1f07..00000000 --- a/app/src/main/java/com/example/android/codelabs/paging/model/RepoSearchResult.kt +++ /dev/null @@ -1,28 +0,0 @@ -/* - * 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.model - -import java.lang.Exception - -/** - * RepoSearchResult from a search, which contains List holding query data, - * and a String of network error state. - */ -sealed class RepoSearchResult { - data class Success(val data: List) : RepoSearchResult() - data class Error(val error: Exception) : RepoSearchResult() -} 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..778678d5 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,24 +17,26 @@ 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 +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): RepoViewHolder { 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: RepoViewHolder, position: Int) { + // placeholders are not enabled, so items will never be null + val repoItem = getItem(position)!! + holder.bind(repoItem) } companion object { 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 bef1f07b..8265b9c3 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 @@ -17,22 +17,23 @@ package com.example.android.codelabs.paging.ui import android.os.Bundle +import android.util.Log import android.view.KeyEvent import android.view.View import android.view.inputmethod.EditorInfo import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.ViewModelProvider -import androidx.lifecycle.observe +import androidx.lifecycle.lifecycleScope +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.FlowPreview +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.collect +import kotlinx.coroutines.launch @FlowPreview @ExperimentalCoroutinesApi @@ -41,6 +42,7 @@ class SearchRepositoriesActivity : AppCompatActivity() { private lateinit var binding: ActivitySearchRepositoriesBinding private lateinit var viewModel: SearchRepositoriesViewModel private val adapter = ReposAdapter() + private var searchJob: Job? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) @@ -55,11 +57,20 @@ class SearchRepositoriesActivity : AppCompatActivity() { // add dividers between RecyclerView's row items val decoration = DividerItemDecoration(this, DividerItemDecoration.VERTICAL) binding.list.addItemDecoration(decoration) - setupScrollListener() - initAdapter() + binding.list.adapter = adapter + adapter.addLoadStateListener { loadType, loadState -> + Log.d("SearchRepositoriesActivity", "adapter load: type = $loadType state = $loadState") + if (loadState is LoadState.Error) { + Toast.makeText( + this, + "\uD83D\uDE28 Wooops $loadState.message}", + Toast.LENGTH_LONG + ).show() + } + } val query = savedInstanceState?.getString(LAST_SEARCH_QUERY) ?: DEFAULT_QUERY - viewModel.searchRepo(query) + search(query) initSearch(query) } @@ -68,25 +79,6 @@ class SearchRepositoriesActivity : AppCompatActivity() { outState.putString(LAST_SEARCH_QUERY, binding.searchRepo.text.trim().toString()) } - 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() - } - } - } - } - private fun initSearch(query: String) { binding.searchRepo.setText(query) @@ -112,8 +104,21 @@ class SearchRepositoriesActivity : AppCompatActivity() { binding.searchRepo.text.trim().let { if (it.isNotEmpty()) { binding.list.scrollToPosition(0) - viewModel.searchRepo(it.toString()) - adapter.submitList(null) + search(it.toString()) + // TODO how to clear the list + // might not need it because of how Paging works +// adapter.collectFrom(PagingData.empty()) + } + } + } + + 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).collect { + Log.d("SearchRepositoriesActivity", "query: $query, collecting $it") + adapter.presentData(it) } } } @@ -128,20 +133,6 @@ class SearchRepositoriesActivity : AppCompatActivity() { } } - 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) - } - }) - } - companion object { private const val LAST_SEARCH_QUERY: String = "last_search_query" private const val DEFAULT_QUERY = "Android" 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 e7f893a3..63c10015 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,10 +16,15 @@ 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.* +import com.example.android.codelabs.paging.model.Repo +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.FlowPreview +import kotlinx.coroutines.flow.Flow /** * ViewModel for the [SearchRepositoriesActivity] screen. @@ -29,33 +34,23 @@ import kotlinx.coroutines.* @FlowPreview class SearchRepositoriesViewModel(private val repository: GithubRepository) : ViewModel() { - companion object { - private const val VISIBLE_THRESHOLD = 5 - } - - private val queryLiveData = MutableLiveData() - val repoResult: LiveData = queryLiveData.switchMap { - liveData { - val repos = repository.getSearchResultStream(it).asLiveData(Dispatchers.Main) - emitSource(repos) - } - } + @Volatile + private var currentQueryValue: String? = null + @Volatile + private var currentSearchResult: Flow>? = null /** * Search a repository based on a query string. */ - fun searchRepo(queryString: String) { - queryLiveData.postValue(queryString) - } - - 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 = repository.getSearchResultStream(queryString) + .cachedIn(viewModelScope) + currentSearchResult = newResult + return newResult } } \ No newline at end of file diff --git a/build.gradle b/build.gradle index 06a79fc9..132d3a12 100644 --- a/build.gradle +++ b/build.gradle @@ -35,6 +35,7 @@ allprojects { repositories { google() jcenter() + maven { url 'https://ci.android.com/builds/submitted/6261180/androidx_snapshot/latest/repository' } } } @@ -51,7 +52,7 @@ ext { materialVersion = '1.1.0' archComponentsVersion = '2.2.0' roomVersion = '2.2.4' - pagingVersion = '2.1.0-alpha01' + pagingVersion = '3.0.0-alpha01' retrofitVersion = '2.6.0' okhttpLoggingInterceptorVersion = '4.0.0' coroutines = '1.3.0'