Introduce rememberGlobally
This commit is contained in:
1 parent
39a4b03bc3
commit
8926d74378
2 files changed
+36
-1
No files matched your search
@@ -0,0 +1,34 @@
|
||||
package com.hippo.ehviewer.ui.compose
|
||||
|
||||
import androidx.collection.lruCache
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.currentCompositeKeyHash
|
||||
import androidx.compose.runtime.remember
|
||||
|
||||
private val remembered = lruCache<String, Any>(1)
|
||||
|
||||
@Composable
|
||||
fun <T : Any> rememberGlobally(
|
||||
vararg inputs: Any?,
|
||||
key: String? = null,
|
||||
init: () -> T,
|
||||
): T {
|
||||
// key is the one provided by the user or the one generated by the compose runtime
|
||||
val finalKey = if (!key.isNullOrEmpty()) {
|
||||
key
|
||||
} else {
|
||||
currentCompositeKeyHash.toString(36)
|
||||
}
|
||||
// value is restored using the registry or created via [init] lambda
|
||||
val value = remember(*inputs) {
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
val restored = remembered[finalKey] as? T
|
||||
restored ?: init()
|
||||
}
|
||||
|
||||
LaunchedEffect(finalKey) {
|
||||
remembered.put(finalKey, value)
|
||||
}
|
||||
return value
|
||||
}
|
||||
@@ -57,6 +57,7 @@ import com.hippo.ehviewer.coil.imageRequest
|
||||
import com.hippo.ehviewer.coil.justDownload
|
||||
import com.hippo.ehviewer.ui.compose.data.EhPreviewItem
|
||||
import com.hippo.ehviewer.ui.compose.rememberDialogState
|
||||
import com.hippo.ehviewer.ui.compose.rememberGlobally
|
||||
import com.hippo.ehviewer.ui.compose.setMD3Content
|
||||
import com.hippo.ehviewer.ui.legacy.recyclerview.calculateSuitableSpanCount
|
||||
import com.hippo.ehviewer.ui.navToReader
|
||||
@@ -118,7 +119,7 @@ class GalleryPreviewScreen : Fragment() {
|
||||
initialKey = goto
|
||||
}
|
||||
|
||||
val previewPagesMap = remember { mutableMapOf<Int, PreviewPage>().apply { put(1, galleryDetail.previewList) } }
|
||||
val previewPagesMap = rememberGlobally { mutableMapOf<Int, PreviewPage>().apply { put(1, galleryDetail.previewList) } }
|
||||
val data = remember(initialKey) {
|
||||
Pager(PagingConfig(1, prefetchDistance = 4, enablePlaceholders = false, initialLoadSize = 1), initialKey) {
|
||||
object : PagingSource<Int, PreviewPage>() {
|
||||
|
||||
Reference in new issue
Block a user