Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce MutatedEffect #131

Merged
merged 2 commits into from
Nov 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ data class MutationConfig internal constructor(
companion object {
val Default = MutationConfig(
mapper = MutationObjectMapper.Default,
optimizer = MutationRecompositionOptimizer.Enabled,
optimizer = MutationRecompositionOptimizer.Disabled,
strategy = MutationStrategy.Default,
marker = Marker.None
)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
// Copyright 2024 Soil Contributors
// SPDX-License-Identifier: Apache-2.0

package soil.query.compose.util

import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.saveable.Saver
import androidx.compose.runtime.saveable.autoSaver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import kotlinx.coroutines.flow.filterNotNull
import soil.query.compose.MutationObject
import soil.query.compose.MutationSuccessObject

/**
* A Composable function to trigger side effects when a Mutation is successfully processed.
*
* By using this function, you can receive the result of a successful Mutation via [block].
* This is particularly useful when working with [MutationObject.mutateAsync].
*
* @param T Type of the return value from the mutation.
* @param U Type of the key to identify whether the Mutation has already been handled.
* @param mutation The MutationObject whose result will be observed.
* @param keySelector A function to calculate a key to identify whether the Mutation has already been handled.
* The key is compared upon the next success.
* @param keySaver A Saver to persist and restore the last consumed key.
* @param block A callback to handle the result of the Mutation. This is called only when the key differs from the previous one.
*/
@Composable
fun <T, U : Any> MutatedEffect(
mutation: MutationObject<T, *>,
keySelector: (MutationSuccessObject<T, *>) -> U,
keySaver: Saver<U?, out Any> = autoSaver(),
block: suspend (data: T) -> Unit
) {
val mutationState by rememberUpdatedState(mutation)
var lastConsumedKey by rememberSaveable(stateSaver = keySaver) { mutableStateOf(null) }
LaunchedEffect(Unit) {
snapshotFlow { mutationState as? MutationSuccessObject }
.filterNotNull()
.collect {
val mutatedKey = keySelector(it)
if (lastConsumedKey != mutatedKey) {
lastConsumedKey = mutatedKey
block(it.data)
}
}
}
}

/**
* A Composable function to trigger side effects when a Mutation is successfully processed.
*
* This function uses [MutationObject.replyUpdatedAt] as the key.
* If you need to use a different key, use [MutatedEffect] with the `keySelector` parameter.
*
* **NOTE:**
* If Mutation optimization is enabled, you must explicitly specify a `keySelector`.
* This is because [MutationObject.replyUpdatedAt] is omitted during optimization and will always be `0`.
*
* @param T Type of the return value from the mutation.
* @param mutation The MutationObject whose result will be observed.
*/
@Composable
inline fun <T> MutatedEffect(
mutation: MutationObject<T, *>,
noinline block: suspend (data: T) -> Unit
) {
MutatedEffect(
mutation = mutation,
keySelector = { it.replyUpdatedAt },
block = block
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
// Copyright 2024 Soil Contributors
// SPDX-License-Identifier: Apache-2.0

package soil.query.compose.util

import androidx.compose.foundation.layout.Column
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.test.ExperimentalTestApi
import androidx.compose.ui.test.assertTextEquals
import androidx.compose.ui.test.hasTestTag
import androidx.compose.ui.test.hasText
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.runComposeUiTest
import androidx.compose.ui.test.waitUntilExactlyOneExists
import kotlinx.coroutines.launch
import soil.query.MutationId
import soil.query.MutationKey
import soil.query.SwrCache
import soil.query.SwrCacheScope
import soil.query.buildMutationKey
import soil.query.compose.SwrClientProvider
import soil.query.compose.rememberMutation
import soil.testing.UnitTest
import kotlin.test.Test

@ExperimentalTestApi
class MutatedEffectTest : UnitTest() {

@Test
fun testMutatedEffect() = runComposeUiTest {
val key = TestMutationKey()
val client = SwrCache(coroutineScope = SwrCacheScope())
setContent {
SwrClientProvider(client) {
val mutation = rememberMutation(key)
var mutatedCount by remember { mutableIntStateOf(0) }
val scope = rememberCoroutineScope()
Column {
Button(
onClick = { scope.launch { mutation.mutateAsync("foo") } },
modifier = Modifier.testTag("mutation")
) {
Text("Mutate")
}
Text(
"${mutation.mutatedCount}",
modifier = Modifier.testTag("count")
)
(1..mutatedCount).forEach { result ->
Text(
"Mutated: $result",
modifier = Modifier.testTag("result$result")
)
}
}
MutatedEffect(mutation) {
mutatedCount++
}
}
}

waitForIdle()
onNodeWithTag("result").assertDoesNotExist()
onNodeWithTag("mutation").performClick()

waitUntilExactlyOneExists(hasTestTag("result1"))
onNodeWithText("Mutated: 1").assertExists()
onNodeWithTag("count").assertTextEquals("1")

onNodeWithTag("mutation").performClick()

waitUntilExactlyOneExists(hasTestTag("result2"))
onNodeWithText("Mutated: 2").assertExists()
onNodeWithTag("count").assertTextEquals("2")
}

@Test
fun testMutatedEffect_withKeySelector() = runComposeUiTest {
val key = TestMutationKey()
val client = SwrCache(coroutineScope = SwrCacheScope())
setContent {
SwrClientProvider(client) {
val mutation = rememberMutation(key)
var mutatedCount by remember { mutableIntStateOf(0) }
val scope = rememberCoroutineScope()
Column {
Button(
onClick = { scope.launch { mutation.mutateAsync("foo") } },
modifier = Modifier.testTag("mutation")
) {
Text("Mutate")
}
Text(
"${mutation.mutatedCount}",
modifier = Modifier.testTag("count")
)
(1..mutatedCount).forEach { result ->
Text(
"Mutated: $result",
modifier = Modifier.testTag("result$result")
)
}
}
MutatedEffect(
mutation = mutation,
keySelector = { it.data }
) {
mutatedCount++
}
}
}

waitForIdle()
onNodeWithTag("result").assertDoesNotExist()
onNodeWithTag("mutation").performClick()

waitUntilExactlyOneExists(hasTestTag("result1"))
onNodeWithText("Mutated: 1").assertExists()
onNodeWithTag("count").assertTextEquals("1")

onNodeWithTag("mutation").performClick()

waitUntilExactlyOneExists(hasTestTag("count") and hasText("2"))
// The key is the same as the first mutation result, so the MutatedEffect is not called.
onNodeWithText("Mutated: 2").assertDoesNotExist()
onNodeWithTag("count").assertTextEquals("2")
}


private class TestMutationKey : MutationKey<String, String> by buildMutationKey(
id = MutationId("test"),
mutate = { variable ->
"Mutated: $variable"
}
)
}