Skip to content

Commit

Permalink
Merge pull request #132 from soil-kt/namespace-auto-composition-keyhash
Browse files Browse the repository at this point in the history
Add Namespace Extension Property `autoCompositionKeyHash`
  • Loading branch information
ogaclejapan authored Nov 24, 2024
2 parents 284d496 + 4bd7b0a commit 2d79f86
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ import soil.playground.query.key.ExampleSubscriptionKey
import soil.query.annotation.ExperimentalSoilQueryApi
import soil.query.compose.SubscriptionObject
import soil.query.compose.rememberSubscription
import soil.query.compose.util.auto
import soil.query.compose.util.autoCompositionKeyHash
import soil.query.core.Namespace

@OptIn(ExperimentalSoilQueryApi::class)
@Composable
fun rememberExampleSubscription(): SubscriptionObject<String> {
return rememberSubscription(
key = ExampleSubscriptionKey(Namespace.auto())
key = ExampleSubscriptionKey(Namespace.autoCompositionKeyHash)
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
package soil.query.compose.util

import androidx.compose.runtime.Composable
import androidx.compose.runtime.currentCompositeKeyHash
import androidx.compose.runtime.saveable.Saver
import androidx.compose.runtime.saveable.rememberSaveable
import soil.query.core.Namespace
Expand All @@ -22,7 +23,34 @@ fun Namespace.Companion.auto(): Namespace {
}

internal val Namespace.Companion.Saver
get() = Saver<Namespace, String>(
save = { it.value },
restore = { Namespace(it) }
)
get() = Saver<Namespace, String>(save = { it.value }, restore = { Namespace(it) })


/**
* Automatically generated value for `mutationId` and `subscriptionId`.
*
* This property is useful for generating a unique namespace when a key,
* such as `MutationKey` or `SubscriptionKey`, is used within a single Composable function.
*
* **NOTE:**
* This property must only be used within a Composable function restricted to a single key
* (either Mutation or Subscription). It is intended to be used in a custom Composable function
* dedicated to handling a single key. For other use cases, it is recommended to use the [auto] function.
*
* Example:
* ```kotlin
* @Composable
* fun rememberCreatePost(): MutationObject<Post> {
* return rememberMutation(CreatePostKey(Namespace.autoCompositionKeyHash))
* }
* ```
*/
val Namespace.Companion.autoCompositionKeyHash: Namespace
@Composable
get() {
val keyHash = currentCompositeKeyHash.toString(MaxSupportedRadix)
return Namespace("auto/$keyHash")
}

// https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:compose/runtime/runtime-saveable/src/commonMain/kotlin/androidx/compose/runtime/saveable/RememberSaveable.kt?q=MaxSupportedRadix
private const val MaxSupportedRadix: Int = 36

0 comments on commit 2d79f86

Please sign in to comment.