I am implementing a use-case where I am using Paging library to load a list of Books from my remote api. The remote api gives a list of Books for a particular page number.I am adding a simple local cache using a Map data structure to cache the list so that if the List for a particular page is already present in the cache we don't do a remote api call. If the List of Books for a particular page in not present in the cache we do a remote api request using my Repository implementation as given below. For the time being I am not handling cache invalidation
The components of my implementation is as follows,
A model class for Book
data class Book(val name: String, val imageUrl: String)
A RemoteMediator to load data from remote api. It is responsible for loading List from remote api and save it in local cache.
class BookRemoteMediator(val remoteRepository: Repository) : RemoteMediator<Int, Book>{ override suspend fun load(loadType: LoadType, state: PagingState<Int, Book>): MediatorResult {
}
}
class Repository(val apiClient: ApiClient){
suspend fun doRequest(page : Int) : List<Book>{ //Get data from remote using apiClient }
}
PagingSource to load data from local cache.
class LocalCache(){ val cache: Map<Int, List> = mutableMapOf()
fun addToCache(page : Int, books : List){ cache.put(page, books) }
fun getFromCache(int page){ cache.get(page) }
}
class BookPagingSource(val cache : LocalCache): PagingSource<Int, Book>(){ override fun getRefreshKey(state: PagingState<Int, String>): Int? { TODO("Not yet implemented") }
override suspend fun load(params: PagingSource.LoadParams<Int>): PagingSource.LoadResult<Int, Book> {
//Get data from cache here }
}
A Pager instance which returns a flow.
val pager: Flow<PagingData> = Pager(PagingConfig(pageSize = 20), initialKey = 0, pagingSourceFactory = {
BookPagingSource(cache) }, remoteMediator = BookRemoteMediator()).flow
How do my PagingSource trigger to load List from RemoteMediator in this case? What should I return from load methods of RemoteMediator and PagingSource?