-
Notifications
You must be signed in to change notification settings - Fork 308
Add snippets for new Compose State DAC guides #741
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
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
167 changes: 167 additions & 0 deletions
167
...ets/src/main/java/com/example/compose/snippets/state/RememberAndRetainObserverSnippets.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,167 @@ | ||
| /* | ||
| * Copyright 2025 The Android Open Source Project | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * https://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| package com.example.compose.snippets.state | ||
|
|
||
| import androidx.compose.runtime.Composable | ||
| import androidx.compose.runtime.RememberObserver | ||
| import androidx.compose.runtime.remember | ||
| import kotlinx.coroutines.CoroutineScope | ||
| import kotlinx.coroutines.Dispatchers | ||
| import kotlinx.coroutines.Job | ||
| import kotlinx.coroutines.launch | ||
|
|
||
| private object RememberAndRetainObserverSnippets1 { | ||
| interface RememberObserver : androidx.compose.runtime.RememberObserver { | ||
| override fun onAbandoned() {} | ||
| override fun onForgotten() {} | ||
| override fun onRemembered() {} | ||
| } | ||
|
|
||
| // [START android_compose_state_observers_initialize_in_remember] | ||
| class MyComposeObject : RememberObserver { | ||
| private val job = Job() | ||
| private val coroutineScope = CoroutineScope(Dispatchers.Main + job) | ||
|
|
||
| init { | ||
| // Not recommended: This will cause work to begin during composition instead of | ||
| // with other effects. Move this into onRemembered(). | ||
| coroutineScope.launch { loadData() } | ||
| } | ||
|
|
||
| override fun onRemembered() { | ||
| // Recommended: Move any cancellable or effect-driven work into the onRemembered | ||
| // callback. If implementing RetainObserver, this should go in onRetained. | ||
| coroutineScope.launch { loadData() } | ||
| } | ||
|
|
||
| private suspend fun loadData() { /* ... */ } | ||
|
|
||
| // ... | ||
| } | ||
| // [END android_compose_state_observers_initialize_in_remember] | ||
| } | ||
|
|
||
| private object RememberAndRetainObserverSnippets2 { | ||
| interface RememberObserver : androidx.compose.runtime.RememberObserver { | ||
| override fun onAbandoned() {} | ||
| override fun onForgotten() {} | ||
| override fun onRemembered() {} | ||
| } | ||
|
|
||
| // [START android_compose_state_observers_teardown_in_forget] | ||
| class MyComposeObject : RememberObserver { | ||
| private val job = Job() | ||
| private val coroutineScope = CoroutineScope(Dispatchers.Main + job) | ||
|
|
||
| // ... | ||
|
|
||
| override fun onForgotten() { | ||
| // Cancel work launched from onRemembered. If implementing RetainObserver, onRetired | ||
| // should cancel work launched from onRetained. | ||
| job.cancel() | ||
| } | ||
|
|
||
| override fun onAbandoned() { | ||
| // If any work was launched by the constructor as part of remembering the object, | ||
| // you must cancel that work in this callback. For work done as part of the construction | ||
| // during retain, this code should will appear in onUnused. | ||
| job.cancel() | ||
| } | ||
| } | ||
| // [END android_compose_state_observers_teardown_in_forget] | ||
| } | ||
|
|
||
| private object RememberAndRetainObserverSnippets3 { | ||
| interface RememberObserver : androidx.compose.runtime.RememberObserver { | ||
| override fun onAbandoned() {} | ||
| override fun onForgotten() {} | ||
| override fun onRemembered() {} | ||
| } | ||
|
|
||
| // [START android_compose_state_observers_private_implementation] | ||
| abstract class MyManager | ||
|
|
||
| class MyComposeManager : MyManager() { | ||
| // Callers that construct this object must manually call initialize and teardown | ||
| fun initialize() { /*...*/ } | ||
| fun teardown() { /*...*/ } | ||
| } | ||
|
|
||
| @Composable | ||
| fun rememberMyManager(): MyManager { | ||
| // Protect the RememberObserver implementation by never exposing it outside the library | ||
| return remember { | ||
| object : RememberObserver { | ||
| val manager = MyComposeManager() | ||
| override fun onRemembered() = manager.initialize() | ||
| override fun onForgotten() = manager.teardown() | ||
| override fun onAbandoned() { /* Nothing to do if manager hasn't initialized */ } | ||
| } | ||
| }.manager | ||
| } | ||
| // [END android_compose_state_observers_private_implementation] | ||
| } | ||
|
|
||
| private object RememberAndRetainObserverSnippets4 { | ||
| class Foo : RememberObserver { | ||
| override fun onRemembered() {} | ||
| override fun onForgotten() {} | ||
| override fun onAbandoned() {} | ||
| } | ||
|
|
||
| class Bar(val foo: Foo) | ||
|
|
||
| @Composable fun rememberFoo() = remember { Foo() } | ||
|
|
||
| @Composable | ||
| fun Snippet() { | ||
| // [START android_compose_state_observers_transitive_remember] | ||
| val foo: Foo = rememberFoo() | ||
|
|
||
| // Acceptable: | ||
| val bar: Bar = remember { Bar(foo) } | ||
|
|
||
| // Recommended key usage: | ||
| val barWithKey: Bar = remember(foo) { Bar(foo) } | ||
| // [END android_compose_state_observers_transitive_remember] | ||
| } | ||
| } | ||
|
|
||
| private object RememberAndRetainObserverSnippets5 { | ||
| class Foo : RememberObserver { | ||
| override fun onRemembered() {} | ||
| override fun onForgotten() {} | ||
| override fun onAbandoned() {} | ||
| } | ||
|
|
||
| class Bar(val foo: Foo) | ||
|
|
||
| @Composable fun rememberFoo() = remember { Foo() } | ||
|
|
||
| // [START android_compose_state_observers_transitive_remember_params] | ||
| @Composable | ||
| fun MyComposable( | ||
| parameter: Foo | ||
| ) { | ||
| // Acceptable: | ||
| val derivedValue = remember { Bar(parameter) } | ||
|
|
||
| // Also Acceptable: | ||
| val derivedValueWithKey = remember(parameter) { Bar(parameter) } | ||
| } | ||
| // [END android_compose_state_observers_transitive_remember_params] | ||
| } | ||
134 changes: 134 additions & 0 deletions
134
compose/snippets/src/main/java/com/example/compose/snippets/state/StateLifespansSnippets.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,134 @@ | ||
| /* | ||
| * Copyright 2025 The Android Open Source Project | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * https://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| package com.example.compose.snippets.state | ||
|
|
||
| import androidx.compose.runtime.Composable | ||
| import androidx.compose.runtime.getValue | ||
| import androidx.compose.runtime.mutableStateOf | ||
| import androidx.compose.runtime.remember | ||
| import androidx.compose.runtime.retain.retain | ||
| import androidx.compose.runtime.saveable.SaverScope | ||
| import androidx.compose.runtime.saveable.listSaver | ||
| import androidx.compose.runtime.saveable.rememberSaveable | ||
| import androidx.compose.runtime.saveable.rememberSerializable | ||
| import androidx.compose.ui.platform.LocalContext | ||
| import androidx.media3.exoplayer.ExoPlayer | ||
| import kotlinx.serialization.Serializable | ||
| import kotlinx.serialization.serializer | ||
|
|
||
| private object StateLifespansSnippets1 { | ||
| // [START android_compose_state_lifespans_saver] | ||
| data class Size(val x: Int, val y: Int) { | ||
| object Saver : androidx.compose.runtime.saveable.Saver<Size, Any> by listSaver( | ||
| save = { listOf(it.x, it.y) }, | ||
| restore = { Size(it[0], it[1]) } | ||
| ) | ||
| } | ||
|
|
||
| @Composable | ||
| fun rememberSize(x: Int, y: Int) { | ||
| rememberSaveable(x, y, saver = Size.Saver) { | ||
| Size(x, y) | ||
| } | ||
| } | ||
| // [END android_compose_state_lifespans_saver] | ||
| } | ||
|
|
||
| private object StateLifespansSnippets2 { | ||
| // [START android_compose_state_lifespans_retain_invocation] | ||
| @Composable | ||
| fun MediaPlayer() { | ||
| // Use the application context to avoid a memory leak | ||
| val applicationContext = LocalContext.current.applicationContext | ||
| val exoPlayer = retain { ExoPlayer.Builder(applicationContext).apply { /* ... */ }.build() } | ||
| // ... | ||
| } | ||
| // [END android_compose_state_lifespans_retain_invocation] | ||
| } | ||
|
|
||
| private object StateLifespansSnippets3 { | ||
|
|
||
| @Serializable | ||
| object AnotherSerializableType | ||
|
|
||
| private fun <T> defaultValue(): T = TODO() | ||
|
|
||
| // [START android_compose_state_lifespans_combined_retain_save] | ||
| @Composable | ||
| fun rememberAndRetain(): CombinedRememberRetained { | ||
| val saveData = rememberSerializable(serializer = serializer<ExtractedSaveData>()) { | ||
| ExtractedSaveData() | ||
| } | ||
| val retainData = retain { ExtractedRetainData() } | ||
| return remember(saveData, retainData) { | ||
| CombinedRememberRetained(saveData, retainData) | ||
| } | ||
| } | ||
|
|
||
| @Serializable | ||
| data class ExtractedSaveData( | ||
| // All values that should persist process death should be managed by this class. | ||
| var savedData: AnotherSerializableType = defaultValue() | ||
| ) | ||
|
|
||
| class ExtractedRetainData { | ||
| // All values that should be retained should appear in this class. | ||
| // It's possible to manage a CoroutineScope using RetainObserver. | ||
| // See the full sample for details. | ||
| var retainedData = Any() | ||
| } | ||
|
|
||
| class CombinedRememberRetained( | ||
| private val saveData: ExtractedSaveData, | ||
| private val retainData: ExtractedRetainData, | ||
| ) { | ||
| fun doAction() { | ||
| // Manipulate the retained and saved state as needed. | ||
| } | ||
| } | ||
| // [END android_compose_state_lifespans_combined_retain_save] | ||
| } | ||
|
|
||
| private object StateLifespansSnippets4 { | ||
| // [START android_compose_state_lifespans_remember_factory_functions] | ||
| @Composable | ||
| fun rememberImageState( | ||
| imageUri: String, | ||
| initialZoom: Float = 1f, | ||
| initialPanX: Int = 0, | ||
| initialPanY: Int = 0 | ||
| ): ImageState { | ||
| return rememberSaveable(imageUri, saver = ImageState.Saver) { | ||
| ImageState( | ||
| imageUri, initialZoom, initialPanX, initialPanY | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| data class ImageState( | ||
| val imageUri: String, | ||
| val zoom: Float, | ||
| val panX: Int, | ||
| val panY: Int | ||
| ) { | ||
| object Saver : androidx.compose.runtime.saveable.Saver<ImageState, Any> by listSaver( | ||
| save = { listOf(it.imageUri, it.zoom, it.panX, it.panY) }, | ||
| restore = { ImageState(it[0] as String, it[1] as Float, it[2] as Int, it[3] as Int) } | ||
| ) | ||
| } | ||
| // [END android_compose_state_lifespans_remember_factory_functions] | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.