Skip to content

Commit

Permalink
[resources] Use cached value synchronously on web. (#4893)
Browse files Browse the repository at this point in the history
The change speeds resources web rendering up by the reading a cached
value instantly by request (it was being dispatched to the end of the UI
queue in `LaunchedEffect`)

## Release Notes
### Features - Resources
- Speed resources web rendering up by the reading a cached value
instantly
  • Loading branch information
terrakok committed May 30, 2024
1 parent c519a69 commit 2305ea7
Showing 1 changed file with 24 additions and 13 deletions.
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package org.jetbrains.compose.resources

import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.launch

@Composable
internal actual fun <T> rememberResourceState(
Expand All @@ -13,11 +15,14 @@ internal actual fun <T> rememberResourceState(
block: suspend (ResourceEnvironment) -> T
): State<T> {
val environment = LocalComposeEnvironment.current.rememberEnvironment()
val state = remember(key1) { mutableStateOf(getDefault()) }
LaunchedEffect(key1) {
state.value = block(environment)
val scope = rememberCoroutineScope()
return remember(key1) {
val mutableState = mutableStateOf(getDefault())
scope.launch(start = CoroutineStart.UNDISPATCHED) {
mutableState.value = block(environment)
}
mutableState
}
return state
}

@Composable
Expand All @@ -28,11 +33,14 @@ internal actual fun <T> rememberResourceState(
block: suspend (ResourceEnvironment) -> T
): State<T> {
val environment = LocalComposeEnvironment.current.rememberEnvironment()
val state = remember(key1, key2) { mutableStateOf(getDefault()) }
LaunchedEffect(key1, key2) {
state.value = block(environment)
val scope = rememberCoroutineScope()
return remember(key1, key2) {
val mutableState = mutableStateOf(getDefault())
scope.launch(start = CoroutineStart.UNDISPATCHED) {
mutableState.value = block(environment)
}
mutableState
}
return state
}

@Composable
Expand All @@ -44,9 +52,12 @@ internal actual fun <T> rememberResourceState(
block: suspend (ResourceEnvironment) -> T
): State<T> {
val environment = LocalComposeEnvironment.current.rememberEnvironment()
val state = remember(key1, key2, key3) { mutableStateOf(getDefault()) }
LaunchedEffect(key1, key2, key3) {
state.value = block(environment)
val scope = rememberCoroutineScope()
return remember(key1, key2, key3) {
val mutableState = mutableStateOf(getDefault())
scope.launch(start = CoroutineStart.UNDISPATCHED) {
mutableState.value = block(environment)
}
mutableState
}
return state
}

0 comments on commit 2305ea7

Please sign in to comment.