refactor(android): make ClawViewModel#isPostSaved synchronous

Fixes #403
This commit is contained in:
Harsh Shandilya 2023-10-15 00:45:05 +05:30
parent 46cc0910bf
commit a5af23e330
No known key found for this signature in database
4 changed files with 20 additions and 7 deletions

View file

@ -23,12 +23,11 @@ import me.saket.swipe.SwipeableActionsBox
@Composable
fun ListItem(
item: SavedPost,
isSaved: suspend (SavedPost) -> Boolean,
isSaved: (SavedPost) -> Boolean,
isRead: suspend (String) -> Boolean,
postActions: PostActions,
modifier: Modifier = Modifier,
) {
val saved by produceState(false, item) { value = isSaved(item) }
val read by produceState(false, item.shortId) { value = isRead(item.shortId) }
val commentsAction =
SwipeAction(
@ -41,7 +40,7 @@ fun ListItem(
) {
LobstersCard(
post = item,
isSaved = saved,
isSaved = isSaved(item),
isRead = read,
postActions = postActions,
modifier = modifier,

View file

@ -39,7 +39,7 @@ import eu.bambooapps.material3.pullrefresh.rememberPullRefreshState
fun NetworkPosts(
lazyPagingItems: LazyPagingItems<LobstersPost>,
listState: LazyListState,
isPostSaved: suspend (SavedPost) -> Boolean,
isPostSaved: (SavedPost) -> Boolean,
isPostRead: suspend (String) -> Boolean,
postActions: PostActions,
modifier: Modifier = Modifier,

View file

@ -43,7 +43,7 @@ import kotlinx.coroutines.flow.Flow
fun SearchList(
items: Flow<PagingData<LobstersPost>>,
listState: LazyListState,
isPostSaved: suspend (SavedPost) -> Boolean,
isPostSaved: (SavedPost) -> Boolean,
postActions: PostActions,
searchQuery: String,
setSearchQuery: (String) -> Unit,

View file

@ -44,9 +44,12 @@ import javax.inject.Inject
import kotlinx.collections.immutable.ImmutableMap
import kotlinx.collections.immutable.toImmutableMap
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
@ContributesViewModel
@ -99,6 +102,17 @@ constructor(
var searchQuery by mutableStateOf("")
private val _savedPostsMutex = Mutex()
private var _savedPosts = emptyList<String>()
init {
viewModelScope.launch {
savedPosts.collectLatest {
_savedPostsMutex.withLock { _savedPosts = it.map(SavedPost::shortId) }
}
}
}
private fun mapSavedPosts(items: List<SavedPost>): ImmutableMap<Month, List<SavedPost>> {
val sorted =
items.sortedWith { post1, post2 ->
@ -107,8 +121,8 @@ constructor(
return sorted.groupBy { post -> post.createdAt.toLocalDateTime().month }.toImmutableMap()
}
suspend fun isPostSaved(post: SavedPost): Boolean {
return savedPosts.first().any { savedPost -> savedPost.shortId == post.shortId }
fun isPostSaved(post: SavedPost): Boolean {
return _savedPosts.contains(post.shortId)
}
fun toggleSave(post: SavedPost) {