How to write unit tests for paging library in android - android

I need to write unit tests for doing a paginated network request. First I implemented paging library logic to retrieve the data.
I created a data source class and a repository class to get data from the network request.
This is my data source class
class ListDataSource(
private val networkService: NetworkService,
private val searchKey: String) : PagingSource<Int, ListItem>() {
override fun getRefreshKey(state: PagingState<Int, ListItem>): Int? {
return state.anchorPosition?.let { anchorPosition ->
state.closestPageToPosition(anchorPosition)?.prevKey?.plus(1)
?: state.closestPageToPosition(anchorPosition)?.nextKey?.minus(1)
}
}
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, ListItem> {
val pageNumber: Int = params.key ?: 0
return try {
val response = networkService.getList(
searchTerm = searchKey,
page = pageNumber,
size = 30
)
val listItems = response.response?.list
val nextKey = listItems?.let { nonNullList ->
if (nonNullList.size < 30) {
null
} else {
pageNumber + 1
}
} ?: run {
null
}
LoadResult.Page(
data = listItems.orEmpty(),
prevKey = if (pageNumber == 0) null else pageNumber - 1,
nextKey = nextKey
)
} catch (exception: Exception) {
LoadResult.Error(exception)
}
}}
This is my repository class
class ListPagingRepository(private val service: NetworkService) {
private lateinit var pager: Pager<Int, ListItem>
private lateinit var pagingSource: ListDataSource
fun getListPager(): Pager<Int, ListItem> {
return pager
}
fun isPagerInitialized(): Boolean = this::pager.isInitialized
fun createSource(searchTerm: String) {
pagingSource = ListDataSource(service, searchTerm)
}
fun createPager() {
pager = Pager(
config = PagingConfig(
initialLoadSize = 15,
pageSize = 15,
enablePlaceholders = false,
prefetchDistance = 2
),
pagingSourceFactory = { pagingSource }
)
}}
Inside my viewmodel I the function to do the network call is:
fun getPaginatedList(searchTerm: String): Flow<PagingData<ListItem>> {
listPagingRepository.createSource(searchTerm)
listPagingRepository.createPager()
return if (listPagingRepository.isPagerInitialized()) {
listPagingRepository
.getListPager()
.flow
.cachedIn(viewModelScope)
.map { pagingData -> pagingData.map { listMapper.map(it) } }
} else emptyFlow()
}
How can I test this network request?
Searched for 2 days but nothing that I found helped me.

You should test your implementation, with mocked network responses. An example of such a test with MockK as the mocking framework :
#Test
fun `verify error return from load() when a (types of responses you expect to potentially receive) response is returned` () = runTest {
val mockNetworkService = mockk<NetworkService>(relaxed = true, relaxedUnitFun = true)
val testParams = LoadParams(1, false)
every { mockNetworkService.getList(any(), any(), any()) } returns LoadResponse.Error(YourExpectedException)
val result = ListDataSource(mockNetworkService, "test search").load(testParams)
assertEquals(LoadResponse.Error(YourExpectedException), result)
}

Related

Paging with Jetpack Compose cause infinite retrofit calls

I am trying to implement paging for the TMDB API using paging3 and paging-compose.
Here the source of truth is database and api calls are handled by Remote-mediator.
Repository:
class Repository #Inject constructor(
val database: Database,
private val apiService: ApiService
){
#ExperimentalPagingApi
fun movies(): Flow<PagingData<Movie>> = Pager(
config = PagingConfig(pageSize = 20),
remoteMediator = MovieRemoteMediator(database,apiService),
){
database.movieDao().pagedTopRated()
}.flow
}
RemoteMediator:
#ExperimentalPagingApi
class MovieRemoteMediator(
private val database: Database,
private val networkService: ApiService
) : RemoteMediator<Int, Movie>() {
override suspend fun load(loadType: LoadType, state: PagingState<Int, Movie>): MediatorResult {
val page:Int = when(loadType){
LoadType.REFRESH -> {
val remoteKeys = getRemoteKeyClosestToCurrentPosition(state)
remoteKeys?.nextKey?.minus(1) ?: 1
}
LoadType.PREPEND -> {
val remoteKeys = getRemoteKeyForFirstItem(state)
val prevKey = remoteKeys?.prevKey
?: return MediatorResult.Success(endOfPaginationReached = remoteKeys != null)
prevKey
}
LoadType.APPEND -> {
val remoteKeys = getRemoteKeyForLastItem(state)
val nextKey = remoteKeys?.nextKey
?: return MediatorResult.Success(endOfPaginationReached = remoteKeys != null)
nextKey
}
}
return try {
val response
: MovieResponse = networkService.getTopRatedMovies(page)
val toInsert: MutableList<Movie> = mutableListOf();
for (i in response.results)
toInsert.add(i.mapToMovie());
val endOfPaginationReached = response.page + 1 > response.totalPages
database.withTransaction {
if (loadType == LoadType.REFRESH) {
database.movieKeyDao().clearRemoteKeys()
database.movieDao().clearMovies()
}
val prevKey = if (page == 1) null else page - 1
val nextKey = if (endOfPaginationReached) null else page + 1
val keys = response.results.map {
MovieKey(movieId = it.id, prevKey = prevKey, nextKey = nextKey)
}
database.movieDao().insertMovies(toInsert)
database.movieKeyDao().insertAll(keys)
}
MediatorResult.Success(
endOfPaginationReached = endOfPaginationReached
)
} catch (e: IOException) {
MediatorResult.Error(e)
} catch (e: HttpException) {
MediatorResult.Error(e)
}
}
private suspend fun getRemoteKeyForLastItem(state: PagingState<Int, Movie>): MovieKey? {
// Get the last page that was retrieved, that contained items.
// From that last page, get the last item
return state.pages.lastOrNull() { it.data.isNotEmpty() }?.data?.lastOrNull()
?.let { repo ->
// Get the remote keys of the last item retrieved
database.movieKeyDao().remoteKeysMovieId(repo.id)
}
}
private suspend fun getRemoteKeyForFirstItem(state: PagingState<Int, Movie>): MovieKey? {
// Get the first page that was retrieved, that contained items.
// From that first page, get the first item
return state.pages.firstOrNull { it.data.isNotEmpty() }?.data?.firstOrNull()
?.let { repo ->
// Get the remote keys of the first items retrieved
database.movieKeyDao().remoteKeysMovieId(repo.id)
}
}
private suspend fun getRemoteKeyClosestToCurrentPosition(
state: PagingState<Int, Movie>
): MovieKey? {
// The paging library is trying to load data after the anchor position
// Get the item closest to the anchor position
return state.anchorPosition?.let { position ->
state.closestItemToPosition(position)?.id?.let { repoId ->
database.movieKeyDao().remoteKeysMovieId(repoId)
}
}
}
ViewModel:
#HiltViewModel
class MovieViewModel #Inject constructor(
private val movieRepository: Repository
) : ViewModel() {
#ExperimentalPagingApi
fun getMovies() = movieRepository.movies().cachedIn(viewModelScope)
}
Ui Screen:
#ExperimentalCoilApi
#ExperimentalPagingApi
#Composable
fun MainScreen(){
val viewModel: MovieViewModel = viewModel()
val movieList = viewModel.getMovies().collectAsLazyPagingItems()
LazyColumn{
items(movieList){ movie ->
if (movie != null) {
Card(movie)
}
}
}
}
#ExperimentalCoilApi
#ExperimentalPagingApi
#Composable
fun Main(){
MainScreen()
}
MainActivty.kt
#AndroidEntryPoint
class MainActivity : ComponentActivity() {
#ExperimentalCoilApi
#ExperimentalPagingApi
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
JetpackComposePagingTheme {
// A surface container using the 'background' color from the theme
Surface(color = MaterialTheme.colors.background) {
Main()
}
}
}
}
}
I am following the paging3 Codelab for writing the remoteMediator.
On opening the app, it only loads the first 2 pages and then loops infinitely making infinite retrofit calls
You doesn't do exactly as The Codelab you're referencing suggests: they are creating paging Flow inside init and only update it when the query string changes.
On the other hand, you're calling viewModel.getMovies() on each recomposition which causes your problem. Check out how you should work with side effects in Compose in documentation.
In this particular case, as you don't have any parameters, you can simply create it once in the view model like this:
#HiltViewModel
class MovieViewModel #Inject constructor(
private val movieRepository: Repository
) : ViewModel() {
val moviesPagingFlow = movieRepository.movies().cachedIn(viewModelScope)
}
No idea why but in my case isolating the LazyPagingItems from LazyColumn worked.
Try the following:
#Composable
fun MainScreen(){
val viewModel: MovieViewModel = viewModel()
val movieList = viewModel.getMovies().collectAsLazyPagingItems()
MainScreen(movies = movieList)
}
#Composable
fun MainScreen(movies: LazyPagingItems<Movie>){
LazyColumn{
items(movies){ movie ->
if (movie != null) {
Card(movie)
}
}
}
}

pagination not working when reaches to end of page in paging 3 android?

VideoStatusDataSource.kt
class VideoStatusDataSource(
private val categoryKey: String,
private val videosStatusApi: VideoStatusApiService
) : PagingSource<Int, VideoStatus>() {
companion object {
private const val VIDEO_STARTING_PAGE_INDEX = 0
}
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, VideoStatus> {
return try {
val pageIndex = params.key ?: VIDEO_STARTING_PAGE_INDEX
logger(params.key)
logger(pageIndex)
val response =
videosStatusApi.getVideoStatusByPageNumberAndCategoryName(pageIndex, categoryKey)
val jsonCategoryResponse = response.getAsJsonArray(DATA_KEY)
val videoStatusList: List<VideoStatus> = Gson().fromJson(jsonCategoryResponse)
LoadResult.Page(
data = videoStatusList.orEmpty(),
prevKey = if (pageIndex == VIDEO_STARTING_PAGE_INDEX) null else pageIndex - 1,
nextKey = if (videoStatusList.isEmpty()) null else pageIndex.plus(1)
)
} catch (exception: IOException) {
LoadResult.Error(exception)
} catch (exception: HttpException) {
LoadResult.Error(exception)
} catch (exception: Exception) {
LoadResult.Error(exception)
}
}
override fun getRefreshKey(state: PagingState<Int, VideoStatus>): Int? {
return state.anchorPosition?.let { anchorPosition ->
val anchorPage = state.closestPageToPosition(anchorPosition)
anchorPage?.prevKey?.plus(1) ?: anchorPage?.nextKey?.minus(1)
}
}
}
video-API service is providing 10 results on each page but with this data source class it loads all data at once
I want only the first 10 items to load initially and then use scroll first 10 items it needs to load the next 10 items
here is my paging data repository
MainRepopsitory.kt
fun getVideoStatusPagingData(categoryKey: String): Pager<Int, VideoStatus> =
Pager(
config = PagingConfig(
pageSize = 10
),
pagingSourceFactory = { VideoStatusDataSource(categoryKey, videosStatusApi) }
)
ViewModel
#HiltViewModel
class PagingViewModel #Inject constructor(
private val mainRepository: MainRepository,
#IoDispatcher private val ioDispatcher: CoroutineDispatcher
) : ViewModel() {
fun getCurrentCategoryVideoStatus(categoryKey: String): Flow<PagingData<VideoStatus>> =
mainRepository
.getVideoStatusPagingData(categoryKey)
.flow.cachedIn(viewModelScope)
.flowOn(ioDispatcher)
}
This is how I'm using load function in my paging sources you can get help from this I have five to six paging sources in my app and all have same implementations like this
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Message> {
return try {
val nextPage = params.key ?: 0
chatWithSellerRequest.offset = nextPage.times(PAGE_SIZE_LIMIT)
val response = apiService.getSellerChatResponse(chatWithSellerRequest)
_chatWithSellerResultResponse.value = response.chatWithSellerResult
LoadResult.Page(
data = response.chatWithSellerResult?.messages!!,
prevKey = null,
nextKey = if (response.chatWithSellerResult.messages.isEmpty()) null else nextPage + 1
)
} catch (e: Exception) {
LoadResult.Error(e)
}

Is there a way to implement a cursor based pagination with Paging Library 3.0 in Android?

I am consuming a rest API that uses cursor based pagination to show some results. I am wondering if I can use Paging Library 3.0 to paginate it. I have been looking through some mediums and docs and can't seem to find a way to implement it. If any of you has come around any solution, I would be so happy to hear from it!
The api response pagination looks like this:
"paging": {
"previous": false,
"next": "https://api.acelerala.com/v1/orders/?store_id=4&after=xyz",
"cursors": {
"before": false,
"after": "xyz"
}
}
In kotlin, here example.
In Activity or somewhere:
viewModel.triggerGetMoreData("data").collectLatest {
mAdapter.submitData(it)
}
In viewModel:
fun triggerGetMoreData(data: String): Flow<PagingData<SampleData>> {
val request = ExampleRequest(data)
return exampleRepository.getMoreData(request).cachedIn(viewModelScope)
}
In Repository:
fun getMoreData(request: ExampleRequest): Flow<PagingData<ExampleData>> {
return Pager(
config = PagingConfig(
pageSize = 30,
enablePlaceholders = false
),
pagingSourceFactory = { ExamplePagingSource(service, request) }
).flow
}
and
class ExamplePagingSource (
private val service: ExampleService,
private val request: ExampleRequest): PagingSource<Int, ExampleData>() {
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, ExampleData> {
return try {
val pageIndex = params.key ?: 0
val request = request.copy(index = (request.pageNum.toInt() * pageIndex).toString())
when (val result = service.getMoreData(request)) { // call api
is NetworkResponse.Success -> {
val listData = result.body.items?.toData()?: listOf()
LoadResult.Page(
data = listData,
prevKey = if (pageIndex == 0) null else pageIndex - 1,
nextKey = if (listData.isEmpty()) null else pageIndex + 1
)
}
else -> LoadResult.Error(result.toError())
}
} catch (e: Exception) {
e.printStackTrace()
LoadResult.Error(e)
}
}
}
Thanks to #Đặng Anh Hào I was able to get on track. As my cursor is a String and not at Int, the Paging Source load function looks like this:
override suspend fun load(params: LoadParams<String>): LoadResult<String, Order> {
return try{
val response = service.getOrders(query,params.key?:"",10)
val nextKey = if(response.paging?.cursors?.after=="false") null else response.paging?.cursors?.after
val prevKey = if(response.paging?.cursors?.before=="false") null else response.paging?.cursors?.before
LoadResult.Page(response.data?.toOrderList()?:emptyList(),prevKey,nextKey)
}catch (exception: IOException) {
LoadResult.Error(exception)
} catch (exception: retrofit2.HttpException) {
LoadResult.Error(exception)
}
}
and the onrefreshkey looks like this:
override fun getRefreshKey(state: PagingState<String, Order>): String? {
return state.anchorPosition?.let {
state.closestItemToPosition(it)?.orderId
}
}
The repository method looks like this:
fun getOrdersPaginated(storeId: String): Flow<PagingData<Order>> {
return Pager(
config = PagingConfig(enablePlaceholders = false,pageSize = 10),
pagingSourceFactory = {PagingSource(apiService,storeId)}
).flow
}
And the View Model method is like this:
private val _pagedOrders = MutableLiveData<PagingData<Order>>()
val orders get() = _pagedOrders
private var currentQueryValue: String? = null
private var currentSearchResult: Flow<PagingData<Order>>? = null
fun getOrdersPaginated(storeId: String) {
viewModelScope.launch {
currentQueryValue = storeId
val newResult: Flow<PagingData<Order>> = repository.getOrdersPaginated(storeId)
.cachedIn(viewModelScope)
currentSearchResult = newResult
currentSearchResult!!.collect {
_pagedOrders.value = it
}
}
}
The activity calls the paging like this:
private var searchJob: Job? = null
private fun getOrders() {
viewModel.getOrdersPaginated(storeId)
}
private fun listenForChanges() {
viewModel.orders.observe(this, {
searchJob?.cancel()
searchJob = lifecycleScope.launch {
ordersAdapter.submitData(it)
}
})
}
And finally the adapter is the same as a ListAdapter, the only thing that changes is that it now extends PagingDataAdapter<Order, OrderAdapter.ViewHolder>(OrdersDiffer)
For a more detailed tutorial on how to do it, I read this codelab

Android Paging 3 - experiencing flickers, glitches or jumps in position when scrolling & loading new pages

Hello Guys im using Android Jetpack Paging library 3, I'm creating a news app that implements network + database scenario, and im following the codelab by google https://codelabs.developers.google.com/codelabs/android-paging , im doing it almost like in the codelab i almost matched all the operations shown in the examples https://github.com/android/architecture-components-samples/tree/main/PagingWithNetworkSample.
It works almost as it should...but my backend response is page keyed, i mean response comes with the list of news and the next page url, remote mediator fetches the data, populates the database, repository is set, viewmodel is set...
The problem is :
when recyclerview loads the data , following happens:recyclerview flickers, items jump, are removed , added again and so on.
I dont know why recyclerview or its itemanimator behaves like that , that looks so ugly and glitchy.
More than that, when i scroll to the end of the list new items are fetched and that glitchy and jumping effect is happening again.
I would be very grateful if you could help me, im sitting on it for three days , thank you very much in advance.Here are my code snippets:
#Entity(tableName = "blogs")
data class Blog(
#PrimaryKey(autoGenerate = true)
val databaseid:Int,
#field:SerializedName("id")
val id: Int,
#field:SerializedName("title")
val title: String,
#field:SerializedName("image")
val image: String,
#field:SerializedName("date")
val date: String,
#field:SerializedName("share_link")
val shareLink: String,
#field:SerializedName("status")
val status: Int,
#field:SerializedName("url")
val url: String
) {
var categoryId: Int? = null
var tagId: Int? = null
}
Here's the DAO
#Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertAll(blogs: List<Blog>)
#Query("DELETE FROM blogs")
suspend fun deleteAllBlogs()
#Query("SELECT * FROM blogs WHERE categoryId= :categoryId ORDER BY id DESC")
fun getBlogsSourceUniversal(categoryId:Int?): PagingSource<Int, Blog>
#Query("SELECT * FROM blogs WHERE categoryId= :categoryId AND tagId= :tagId ORDER BY id DESC")
fun getBlogsSourceUniversalWithTags(categoryId:Int?,tagId:Int?): PagingSource<Int, Blog>
NewsDatabaseKt
abstract class NewsDatabaseKt : RoomDatabase() {
abstract fun articleDAOKt(): ArticleDAOKt
abstract fun remoteKeyDao(): RemoteKeyDao
companion object {
#Volatile
private var INSTANCE: NewsDatabaseKt? = null
fun getDatabase(context: Context): NewsDatabaseKt =
INSTANCE ?: synchronized(this) {
INSTANCE ?: buildDatabase(context).also { INSTANCE = it }
}
private fun buildDatabase(context: Context) =
Room.databaseBuilder(context.applicationContext,
NewsDatabaseKt::class.java,
"news_database_kt")
.build()
}
RemoteMediator
#ExperimentalPagingApi
class BlogsRemoteMediator(private val categoryId: Int,
private val service: NewsAPIInterfaceKt,
private val newsDatabase: NewsDatabaseKt,
private val tagId : Int? = null ,
private val initialPage:Int = 1
) : RemoteMediator<Int, Blog>() {
override suspend fun initialize(): InitializeAction {
return InitializeAction.LAUNCH_INITIAL_REFRESH
}
override suspend fun load(loadType: LoadType, state: PagingState<Int, Blog>): MediatorResult {
try {
val page = when (loadType) {
REFRESH ->{
initialPage
}
PREPEND -> {
return MediatorResult.Success(endOfPaginationReached = true)}
APPEND -> {
val remoteKey = newsDatabase.withTransaction {
newsDatabase.remoteKeyDao().remoteKeyByLatest(categoryId.toString())
}
if(remoteKey.nextPageKey == null){
return MediatorResult.Success(endOfPaginationReached = true)
}
remoteKey.nextPageKey.toInt()
}
}
val apiResponse =
if(tagId == null) {
service.getCategoryResponsePage(RU, categoryId, page.toString())
}else{
service.getCategoryTagResponsePage(RU,categoryId,tagId,page.toString())
}
val blogs = apiResponse.blogs
val endOfPaginationReached = blogs.size < state.config.pageSize
newsDatabase.withTransaction {
// clear all tables in the database
if (loadType == LoadType.REFRESH) {
newsDatabase.remoteKeyDao().deleteByLatest(categoryId.toString())
if(tagId == null) {
newsDatabase.articleDAOKt().clearBlogsByCatId(categoryId)
}else {
newsDatabase.articleDAOKt().clearBlogsByCatId(categoryId,tagId)
}
}
blogs.map {blog ->
blog.categoryId = categoryId
if(tagId != null) {
blog.tagId = tagId
}
}
newsDatabase.remoteKeyDao().insert(LatestRemoteKey(categoryId.toString(),
apiResponse.nextPageParam))
newsDatabase.articleDAOKt().insertAll(blogs)
}
return MediatorResult.Success(
endOfPaginationReached = endOfPaginationReached
)
} catch (exception: IOException) {
return MediatorResult.Error(exception)
} catch (exception: HttpException) {
return MediatorResult.Error(exception)
}
}
PagingRepository
class PagingRepository(
private val service: NewsAPIInterfaceKt,
private val databaseKt: NewsDatabaseKt
){
#ExperimentalPagingApi
fun getBlogsResultStreamUniversal(int: Int, tagId : Int? = null) : Flow<PagingData<Blog>>{
val pagingSourceFactory = {
if(tagId == null) {
databaseKt.articleDAOKt().getBlogsSourceUniversal(int)
}else databaseKt.articleDAOKt().getBlogsSourceUniversalWithTags(int,tagId)
}
return Pager(
config = PagingConfig(
pageSize = 1
)
,remoteMediator =
BlogsRemoteMediator(int, service, databaseKt,tagId)
,pagingSourceFactory = pagingSourceFactory
).flow
}
}
BlogsViewmodel
class BlogsViewModel(private val repository: PagingRepository):ViewModel(){
private var currentResultUiModel: Flow<PagingData<UiModel.BlogModel>>? = null
private var categoryId:Int?=null
#ExperimentalPagingApi
fun getBlogsUniversalWithUiModel(int: Int, tagId : Int? = null):
Flow<PagingData<UiModel.BlogModel>> {
val lastResult = currentResultUiModel
if(lastResult != null && int == categoryId){
return lastResult
}
val newResult: Flow<PagingData<UiModel.BlogModel>> =
repository.getBlogsResultStreamUniversal(int, tagId)
.map { pagingData -> pagingData.map { UiModel.BlogModel(it)}}
.cachedIn(viewModelScope)
currentResultUiModel = newResult
categoryId = int
return newResult
}
sealed class UiModel{
data class BlogModel(val blog: Blog) : UiModel()
}
PoliticsFragmentKotlin
#ExperimentalPagingApi
class PoliticsFragmentKotlin : Fragment() {
private lateinit var recyclerView: RecyclerView
private lateinit var pagedBlogsAdapter:BlogsAdapter
lateinit var viewModelKt: BlogsViewModel
lateinit var viewModel:NewsViewModel
private var searchJob: Job? = null
#ExperimentalPagingApi
private fun loadData(categoryId:Int, tagId : Int? = null) {
searchJob?.cancel()
searchJob = lifecycleScope.launch {
viewModelKt.getBlogsUniversalWithUiModel(categoryId, tagId).collectLatest {
pagedBlogsAdapter.submitData(it)
}
}
}
#ExperimentalPagingApi
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_blogs, container, false)
viewModelKt = ViewModelProvider(requireActivity(),Injection.provideViewModelFactory(requireContext())).get(BlogsViewModel::class.java)
viewModel = ViewModelProvider(requireActivity()).get(NewsViewModel::class.java)
pagedBlogsAdapter = BlogsAdapter(context,viewModel)
val decoration = DividerItemDecoration(context, DividerItemDecoration.VERTICAL)
recyclerView = view.findViewById(R.id.politics_recyclerView)
recyclerView.addItemDecoration(decoration)
initAdapter()
loadData(categoryId)
initLoad()
return view
}
private fun initLoad() {
lifecycleScope.launchWhenCreated {
Log.d("meylis", "lqunched loadstate scope")
pagedBlogsAdapter.loadStateFlow
// Only emit when REFRESH LoadState for RemoteMediator changes.
.distinctUntilChangedBy { it.refresh }
// Only react to cases where Remote REFRESH completes i.e., NotLoading.
.filter { it.refresh is LoadState.NotLoading }
.collect { recyclerView.scrollToPosition(0) }
}
}
private fun initAdapter() {
recyclerView.adapter = pagedBlogsAdapter.withLoadStateHeaderAndFooter(
header = BlogsLoadStateAdapter { pagedBlogsAdapter.retry() },
footer = BlogsLoadStateAdapter { pagedBlogsAdapter.retry() }
)
lifecycleScope.launchWhenCreated {
pagedBlogsAdapter.loadStateFlow.collectLatest {
swipeRefreshLayout.isRefreshing = it.refresh is LoadState.Loading
}
}
pagedBlogsAdapter.addLoadStateListener { loadState ->
// Only show the list if refresh succeeds.
recyclerView.isVisible = loadState.source.refresh is LoadState.NotLoading
// Show loading spinner during initial load or refresh.
progressBar.isVisible = loadState.source.refresh is LoadState.Loading
// Show the retry state if initial load or refresh fails.
retryButton.isVisible = loadState.source.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(context, "\uD83D\uDE28 Wooops ${it.error}", Toast.LENGTH_LONG
).show()
}
}
}
companion object {
#JvmStatic
fun newInstance(categoryId: Int, tags : ArrayList<Tag>): PoliticsFragmentKotlin {
val args = Bundle()
args.putInt(URL, categoryId)
args.putSerializable(TAGS,tags)
val fragmentKotlin = PoliticsFragmentKotlin()
fragmentKotlin.arguments = args
Log.d("meylis", "created instance")
return fragmentKotlin
}
}
BlogsAdapter
class BlogsAdapter(var context: Context?, var newsViewModel:NewsViewModel) :
PagingDataAdapter<BlogsViewModel.UiModel.BlogModel, RecyclerView.ViewHolder>
(REPO_COMPARATOR) {
private val VIEW = 10
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return when (viewType) {
VIEW -> MyViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.card_layout, parent, false))
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val uiModel = getItem(position)
if(uiModel == null){
if(uiModel is BlogsViewModel.UiModel.BlogModel){(holder as MyViewHolder).bind(null)}
}
if(uiModel is BlogsViewModel.UiModel.BlogModel){(holder as
MyViewHolder).bind(uiModel.blog)}
}
override fun getItemViewType(position: Int): Int {
return VIEW
}
companion object {
private val REPO_COMPARATOR = object : DiffUtil.ItemCallback<BlogsViewModel.UiModel.BlogModel>() {
override fun areItemsTheSame(oldItem: BlogsViewModel.UiModel.BlogModel, newItem: BlogsViewModel.UiModel.BlogModel): Boolean =
oldItem.blog.title == newItem.blog.title
override fun areContentsTheSame(oldItem: BlogsViewModel.UiModel.BlogModel, newItem: BlogsViewModel.UiModel.BlogModel): Boolean =
oldItem == newItem
}
}
MyViewHolder
class MyViewHolder(var container: View) : RecyclerView.ViewHolder(container) {
var cv: CardView
#JvmField
var mArticle: TextView
var date: TextView? = null
#JvmField
var time: TextView
#JvmField
var articleImg: ImageView
#JvmField
var shareView: View
var button: MaterialButton? = null
#JvmField
var checkBox: CheckBox
var progressBar: ProgressBar
private var blog:Blog? = null
init {
cv = container.findViewById<View>(R.id.cardvmain) as CardView
mArticle = container.findViewById<View>(R.id.article) as TextView
articleImg = container.findViewById<View>(R.id.imgvmain) as ImageView
//button = (MaterialButton) itemView.findViewById(R.id.sharemain);
checkBox = container.findViewById<View>(R.id.checkboxmain) as CheckBox
time = container.findViewById(R.id.card_time)
shareView = container.findViewById(R.id.shareView)
progressBar = container.findViewById(R.id.blog_progress)
}
fun bind(blog: Blog?){
if(blog == null){
mArticle.text = "loading"
time.text = "loading"
articleImg.visibility = View.GONE
}else {
this.blog = blog
mArticle.text = blog.title
time.text = blog.date
if (blog.image.startsWith("http")) {
articleImg.visibility = View.VISIBLE
val options: RequestOptions = RequestOptions()
.centerCrop()
.priority(Priority.HIGH)
GlideImageLoader(articleImg,
progressBar).load(blog.image, options)
} else {
articleImg.visibility = View.GONE
}
}
}
}
NewsApiInterface
interface NewsAPIInterfaceKt {
#GET("sort?")
suspend fun getCategoryResponsePage(#Header("Language") language: String, #Query("category")
categoryId: Int, #Query("page") pageNumber: String): BlogsResponse
#GET("sort?")
suspend fun getCategoryTagResponsePage(#Header("Language") language: String,
#Query("category") categoryId: Int,#Query("tag") tagId:Int, #Query("page") pageNumber: String)
:BlogsResponse
companion object {
fun create(): NewsAPIInterfaceKt {
val logger = HttpLoggingInterceptor()
logger.level = HttpLoggingInterceptor.Level.BASIC
val okHttpClient = UnsafeOkHttpClient.getUnsafeOkHttpClient()
return Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(NewsAPIInterfaceKt::class.java)
}
}
}
I have tried setting initialLoadSize = 1
But the problem still persists
EDIT: Thanks for your answer #dlam , yes, it does , my network API returns the list of results ordered by id. BTW, items do this jump when the application is run offline as well.
Videos when refreshing and loading online
online loading and paging
online loading and paging(2)
Videos when refreshing and loading offline
offline loading and refreshing
Thanks again, here is my gist link https://gist.github.com/Aydogdyshka/7ca3eb654adb91477a42128de2f06ea9
EDIT
Thanks a lot to #dlam, when I set pageSize=10, jumping has disappeared...Then i remembered why i set pageSize=1 in the first place... when i refresh , 3 x pageSize of items are loaded, even if i overrided initialLoadSize = 10 , it still loads 3 x pageSize calling append 2x times after refresh , what could i be doing wrong, what's the correct way to only load first page when i refresh ?
Just following up here from comments:
Setting pageSize = 10 fixes the issue.
The issue was with pageSize being too small, resulting in PagingSource refreshes loading pages that did not cover the viewport. Since source refresh replaces the list and goes through DiffUtil, you need to provide an initialLoadSize that is large enough so that there is some overlap (otherwise scroll position will be lost).
BTW - Paging loads additional data automatically based on PagingConfig.prefetchDistance. If RecyclerView binds items close enough to the edge of the list, it will automatically trigger APPEND / PREPEND loads. This is why the default of initialLoadSize is 3 * pageSize, but if you're still experiencing additional loads, I would suggest either adjusting prefetchDistance, or increasing initialLoadSize further.
config = PagingConfig(
pageSize = PAGE_SIZE,
enablePlaceholders = true,
prefetchDistance = 3* PAGE_SIZE,
initialLoadSize = 2*PAGE_SIZE,
)
make sure enablePlaceholders is set to true and set the page size to around 10 to 20
recyclerview flickers becouse from dao you get items not the same order it was responded from network.
I will suggest you my solution.
we will get items from database order by primary key, databaseid, descending.
first of all delete autogenerated = true.
we will set databaseid manualy, in same order we got items from network.
next lets edit remoteMediator load function.
when (loadType) {
LoadType.PREPEND -> {
blogs.map {
val databaseid = getFirstBlogDatabaseId(state)?.databaseid?:0
movies.forEachIndexed{
index, blog ->
blog.databaseid = roomId - (movies.size -index.toLong())
}
}
}
LoadType.APPEND -> {
val roomId = getLastBlogDatabaseId(state)?.databaseid ?:0
blogs.forEachIndexed{
index, blog ->
blog.databaseid = roomId + index.toLong() + 1
}
}
LoadType.REFRESH -> {
blogs.forEachIndexed{
index, blog ->
blog.databaseid = index.toLong()
}
}
}
private fun getFirstBlogDatabaseId(state: PagingState<Int, Blog>): Blog? {
return state.pages.firstOrNull { it.data.isNotEmpty() }?.data?.firstOrNull()
}
private fun getLastBlogDatabaseId(state: PagingState<Int, Blog>): Blog? {
return state.lastItemOrNull()
}

Paging 3.0 library won't stop fetching items from server

I'm using the Paging 3.0 library to load some data from the server and I'm currently facing an issue where the server returns small number of items i.e 1,2, items. What happens now is the Paging library keeps calling the same endpoint, non-stop. My issue is similar to question 1 and I guess 2 just that mine is with Paging 3.0 and the approach is different.
This is my PagingSource:
private const val STARTING_PAGE_INDEX = 0
class MyPagingSource(
private val apiService: MyProductService,
private val query: String
) : PagingSource<Int, ProductResponse>() {
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, ProductResponse> {
val position = params.key ?: STARTING_PAGE_INDEX
return try {
val response = apiService.searchProduct(STARTING_PAGE_INDEX, query, params.loadSize)
val products = response.data?.records ?: emptyList()
LoadResult.Page(
data = products,
prevKey = if (position == STARTING_PAGE_INDEX) null else position - 1,
nextKey = if (products.isEmpty()) null else position + 1
)
}catch (exception: IOException){
return LoadResult.Error(exception)
}catch (exception: HttpException) {
return LoadResult.Error(exception)
}
}
}
The PagingConfig:
override fun searchProduct(
product: String
): Flow<PagingData<ProductResponse>> {
return Pager(
config = PagingConfig(
pageSize = RECORDS_PER_PAGE,
enablePlaceholders = false,
maxSize = MAX_RECORDS_PER_PAGE
),
pagingSourceFactory = { MyPagingSource(apiService, product) }
).flow
}
companion object {
private const val RECORDS_PER_PAGE = 6
private const val MAX_RECORDS_PER_PAGE = 20
}
In my ViewModel, I have this:
private var currentQueryValue: String? = null
private var currentSearchResult: UIEvent<Flow<PagingData<ProductResponse>>>? = null
fun searchProduct(query: String): UIEvent<Flow<PagingData<ProductResponse>>> {
val lastResult = currentSearchResult
if (query == currentQueryValue && lastResult != null) {
return lastResult
}
currentQueryValue = query
val newResult: Flow<PagingData<ProductResponse>> = dataSource.searchProduct(query)
.cachedIn(viewModelScope)
currentSearchResult = UIEvent(newResult)
return UIEvent(newResult)
}
And in the Fragment, I have this:
private var searchProductJob: Job? = null
private val viewModel by viewModels<MyViewModel> { viewModelProviderFactory }
....
private fun searchProduct(queryString: String) {
searchProductJob?.cancel()
searchProductJob = lifecycleScope.launch {
viewModel.searchProduct(queryString.trim().toLowerCase(Locale.getDefault()))
.getContentIfNotHandled()?.let { pagingData ->
pagingData.collectLatest {
productResultAdapter.submitData(it)
search_product_recycler_view.scrollToPosition(0)
}
}
}
}
I would appreciate any suggestions on how to go about this :)

Categories

Resources