refactor(android): abstract away getMorePosts type

This commit is contained in:
Harsh Shandilya 2022-09-23 16:42:39 +05:30
parent f0cb6d638f
commit eb058cfa3d
No known key found for this signature in database
2 changed files with 9 additions and 3 deletions

View file

@ -13,14 +13,14 @@ import kotlinx.coroutines.withContext
class LobstersPagingSource class LobstersPagingSource
@AssistedInject @AssistedInject
constructor( constructor(
@Assisted private val getMorePosts: suspend (Int) -> List<LobstersPost>, @Assisted private val remoteFetcher: RemoteFetcher<LobstersPost>,
@IODispatcher private val ioDispatcher: CoroutineDispatcher, @IODispatcher private val ioDispatcher: CoroutineDispatcher,
) : PagingSource<Int, LobstersPost>() { ) : PagingSource<Int, LobstersPost>() {
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, LobstersPost> { override suspend fun load(params: LoadParams<Int>): LoadResult<Int, LobstersPost> {
return try { return try {
val page = params.key ?: 1 val page = params.key ?: 1
val posts = withContext(ioDispatcher) { getMorePosts(page) } val posts = withContext(ioDispatcher) { remoteFetcher.getItemsAtPage(page) }
LoadResult.Page( LoadResult.Page(
data = posts, data = posts,
@ -38,6 +38,6 @@ constructor(
@AssistedFactory @AssistedFactory
interface Factory { interface Factory {
fun create(getMorePosts: suspend (Int) -> List<LobstersPost>): LobstersPagingSource fun create(remoteFetcher: RemoteFetcher<LobstersPost>): LobstersPagingSource
} }
} }

View file

@ -0,0 +1,6 @@
package dev.msfjarvis.claw.android.paging
/** SAM interface to abstract over a remote API that fetches paginated content. */
fun interface RemoteFetcher<T> {
suspend fun getItemsAtPage(page: Int): List<T>
}