I have implemented application using codelabs tutorial for new Paging 3 library, which was release week ago. The problem is application is not working in offline mode. It does not retrieve data from Room database.
Tutorial Repo link :- https://github.com/googlecodelabs/android-paging
Code:-
RepoDao.kt
@Dao interface RepoDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertAll(repos: List<Repo>) @Query("SELECT * FROM repos WHERE " + "name LIKE :queryString OR description LIKE :queryString " + "ORDER BY stars DESC, name ASC") fun reposByName(queryString: String): PagingSource<Int, Repo> @Query("DELETE FROM repos") suspend fun clearRepos() }GithubRepository.kt
class GithubRepository( private val service: GithubService, private val database: RepoDatabase ) { fun getSearchResultStream(query: String): Flow<PagingData<Repo>> { val dbQuery = "%${query.replace(' ', '%')}%" val pagingSourceFactory = { database.reposDao().reposByName(dbQuery) } return Pager( config = PagingConfig(pageSize = NETWORK_PAGE_SIZE), remoteMediator = GithubRemoteMediator( query, service, database ), pagingSourceFactory = pagingSourceFactory ).flow } companion object { private const val NETWORK_PAGE_SIZE = 50 } }SearchRepositoriesViewModel.kt
@ExperimentalCoroutinesApi class SearchRepositoriesViewModel(private val repository: GithubRepository) : ViewModel() { private var currentQueryValue: String? = null private var currentSearchResult: Flow<PagingData<Repo>>? = null fun searchRepo(queryString: String): Flow<PagingData<Repo>> { val lastResult = currentSearchResult if (queryString == currentQueryValue && lastResult != null) { return lastResult } currentQueryValue = queryString val newResult: Flow<PagingData<Repo>> = repository.getSearchResultStream(queryString).cachedIn(viewModelScope) currentSearchResult = newResult return newResult } }SearchRepositoriesActivity.kt
@ExperimentalCoroutinesApi class SearchRepositoriesActivity : AppCompatActivity() { ..... private lateinit var viewModel: SearchRepositoriesViewModel private val adapter = ReposAdapter() private var searchJob: Job? = null // this is where adapter get flow data from viewModel // initially this is called with **Android** as a query private fun search(query: String) { searchJob?.cancel() searchJob = lifecycleScope.launch { viewModel.searchRepo(query).collectLatest { adapter.submitData(it) } } } ..... }
Output:- It is just showing the empty recyclerview when application is open in offline mode.