Refine FavouriteStatusRouter observable stateFlow

This commit is contained in:
Lokesh Gidra authored and FooIbar committed 2023-11-01 22:12:07 +08:00
1 parent f2dff038cd
commit 4e54d7f66f
3 files changed
+13 -10

No files matched your search

@@ -67,11 +67,8 @@ fun GalleryInfoListItem(
modifier = Modifier.aspectRatio(DEFAULT_ASPECT).fillMaxSize(),
)
}
val showFav by produceState(false, info.gid) {
value = info.favoriteSlot != NOT_FAVORITED && !isInFavScene
FavouriteStatusRouter.stateFlow(info.gid).collect {
value = it != NOT_FAVORITED && !isInFavScene
}
val showFav by FavouriteStatusRouter.collectAsState(info) {
it != NOT_FAVORITED && !isInFavScene
}
ConstraintLayout(modifier = Modifier.padding(8.dp, 4.dp).fillMaxSize()) {
val (titleRef, uploaderRef, ratingRef, categoryRef, postedRef, favRef, iconsRef) = createRefs()
@@ -79,7 +79,6 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
@@ -715,9 +714,8 @@ class GalleryDetailScene : BaseScene() {
.horizontalScroll(rememberScrollState()),
horizontalArrangement = Arrangement.spacedBy(12.dp, Alignment.CenterHorizontally),
) {
val favored by produceState(initialValue = false) {
value = galleryDetail.favoriteSlot != NOT_FAVORITED
FavouriteStatusRouter.stateFlow(galleryDetail.gid).collect { value = it != NOT_FAVORITED }
val favored by FavouriteStatusRouter.collectAsState(galleryDetail) {
it != NOT_FAVORITED
}
val favButtonText = if (favored) {
galleryDetail.favoriteName ?: stringResource(id = R.string.local_favorites)
@@ -15,11 +15,16 @@
*/
package com.hippo.ehviewer.util
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.remember
import com.hippo.ehviewer.EhDB
import com.hippo.ehviewer.client.data.GalleryInfo
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.transform
import kotlinx.coroutines.launch
@@ -40,5 +45,8 @@ object FavouriteStatusRouter {
val globalFlow = _globalFlow.asSharedFlow()
fun stateFlow(targetGid: Long) = globalFlow.transform { (gid, slot) -> if (targetGid == gid) emit(slot) }
@Composable
inline fun <R> collectAsState(initial: GalleryInfo, crossinline transform: (Int) -> R) = remember(initial) {
globalFlow.transform { (gid, slot) -> if (initial.gid == gid) emit(slot) }.map(transform)
}.collectAsState(transform(initial.favoriteSlot))
}