I'm trying to retrieve paging data from network and database. For this I use paging 3 library.
My problem is that when I start scrolling the list, the requests are sent correctly, but I get incorrect data (the same) from the room database. At the beginning, the data is displayed correctly, but starting from position 70, for example, the database returns the same data.
I tried to find a solution to the problem.
On the stackoverflow, the developers recommended adding a primary key that will be auto-generated and adding sorting by this key. However, this did not help me. Here is my entity:
@Entity(tableName = "tableMovies")
class MovieEntity(
@PrimaryKey(autoGenerate = true) var pK: Long = 0,
@ColumnInfo(name = "movieId") val movieId: String,
@ColumnInfo(name = "movieUrl") val url: String
)
And my dao:
@Query("SELECT * FROM tableMovies ORDER BY pK ASC")
fun getAllMovies(): PagingSource<Int, MovieEntity>
Also my entity for remote keys:
@Entity(tableName = "tableRemoteKeys")
class MovieRemoteKeysEntity(
@PrimaryKey val id: String,
@ColumnInfo(name = "prevPage") val prevPage: Int?,
@ColumnInfo(name = "nextPage") val nextPage: Int?
)
In my RemoteMediator after success get response from network if load type is REFRESH I'm clear movie table and remote keys table. And after I'm adding data from response:
data.page?.let { pageNumber ->
nextPage = pageNumber + 1
prevPage = if (pageNumber <= 1) null else pageNumber - 1
}
val keys = data.movies.map { movie ->
MovieRemoteKeysEntity(
id = movie .id.orEmpty(),
prevPage = prevPage,
nextPage = nextPage
)
}
remoteKeysDao.addAllMovieRemoteKeys(keys)
movieDao.addMovies(data.movies)
My config:
override fun getMovies( ): Flow<PagingData<MovieModel>> {
val pagingSourceFactory = { movieDao.getAllMovies() }
return Pager(
config = PagingConfig(pageSize = 15, enablePlaceholders = false),
remoteMediator = MovieRemoteMediator(
apiService,
appDatabase,
),
pagingSourceFactory = pagingSourceFactory,
).flow.map { pagingData ->
pagingData.map { movie-> mapper.mapToModel(movie) }
}
}
Please help me. I did everything according to the guide, but at some point the database returns the same data to me, despite the fact that I receive a new portion of data from the server. Also visually it looks weird, the list starts jumping.
P.S. I also looked at the contents of the tables in the database. The data was added correctly, according to the portions received from the server.