app: add support for fetching newest posts

Signed-off-by: Harsh Shandilya <me@msfjarvis.dev>
This commit is contained in:
Harsh Shandilya 2021-03-29 11:44:45 +05:30
parent e3c5097035
commit fcd27863a1
No known key found for this signature in database
GPG key ID: 366D7BBAD1031E80
3 changed files with 46 additions and 0 deletions

View file

@ -0,0 +1,33 @@
package dev.msfjarvis.lobsters.data.remote
import androidx.paging.PagingSource
import androidx.paging.PagingState
import dev.msfjarvis.lobsters.data.repo.LobstersRepository
import dev.msfjarvis.lobsters.model.LobstersPost
class NewestPostsPagingSource constructor(
private val lobstersRepository: LobstersRepository,
) : PagingSource<Int, LobstersPost>() {
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, LobstersPost> {
return try {
val page = params.key ?: 1
// Update cache before fetching a list.
// This is done to make sure that we can update the isSaved status of incoming posts.
lobstersRepository.updateCache()
val posts = lobstersRepository.fetchNewestPosts(page)
LoadResult.Page(
data = posts,
prevKey = if (page == 1) null else page - 1,
nextKey = page.plus(1)
)
} catch (e: Exception) {
LoadResult.Error(e)
}
}
override fun getRefreshKey(state: PagingState<Int, LobstersPost>): Int {
return state.pages.size + 1
}
}

View file

@ -30,6 +30,10 @@ class LobstersRepository constructor(
return@withContext lobstersApi.getHottestPosts(page)
}
suspend fun fetchNewestPosts(page: Int): List<LobstersPost> = withContext(Dispatchers.IO) {
return@withContext lobstersApi.getNewestPosts(page)
}
// https://issuetracker.google.com/issues/181221325
@Suppress("NewApi")
suspend fun updateCache() {

View file

@ -9,6 +9,7 @@ import dagger.hilt.android.lifecycle.HiltViewModel
import dev.msfjarvis.lobsters.data.local.SavedPost
import dev.msfjarvis.lobsters.data.preferences.ClawPreferences
import dev.msfjarvis.lobsters.data.remote.HottestPostsPagingSource
import dev.msfjarvis.lobsters.data.remote.NewestPostsPagingSource
import dev.msfjarvis.lobsters.data.repo.LobstersRepository
import javax.inject.Inject
import kotlinx.coroutines.flow.Flow
@ -28,7 +29,11 @@ class LobstersViewModel @Inject constructor(
val hottestPosts = Pager(PagingConfig(25)) {
HottestPostsPagingSource(lobstersRepository).also { hottestPostsPagingSource = it }
}.flow.cachedIn(viewModelScope)
val newestPosts = Pager(PagingConfig(25)) {
NewestPostsPagingSource(lobstersRepository).also { newestPostsPagingSource = it }
}.flow.cachedIn(viewModelScope)
private var hottestPostsPagingSource: HottestPostsPagingSource? = null
private var newestPostsPagingSource: NewestPostsPagingSource? = null
init {
lobstersRepository.isCacheReady.onEach { ready ->
@ -50,6 +55,10 @@ class LobstersViewModel @Inject constructor(
hottestPostsPagingSource?.invalidate()
}
fun reloadNewestPosts() {
newestPostsPagingSource?.invalidate()
}
fun toggleSave(post: SavedPost) {
viewModelScope.launch {
val isSaved = lobstersRepository.isPostSaved(post.shortId)