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

States: Ensure the same 'StateFlow' instance is returned #6

Merged
merged 3 commits into from
Sep 5, 2024

Conversation

sellmair
Copy link
Owner

@sellmair sellmair commented Sep 5, 2024

No description provided.

This is a requirement for compose:
Let's assume we're only consuming a cold flow in a single @composable function
```kotlin
@composable
fun MyWidget() {
    Text(MyState.composeValue())
}
```
Then this 'composeValue' function will internally get the 'StateFlow' and use the 'collectAsState' compose
function to react to the state:
```kotlin
/* Copied form compose */
@composable
fun <T> produceState(
    initialValue: T,
    key1: Any?, // < this key will be the StateFlow which shall be collected
    key2: Any?, // <- this key will be the current coroutine context
    producer: suspend ProduceStateScope<T>.() -> Unit
): State<T> {
    val result = remember { mutableStateOf(initialValue) }
    LaunchedEffect(key1, key2) {
        ProduceStateScopeImpl(result, coroutineContext).producer()
    }
    return result
}
```
As you can see: It is important to return the same (or equal) instance of this 'to be collected' flow
as otherwise the LaunchedEffect will be re-triggered and "subscribe", "unsubscribe" loop will happen.
@sellmair sellmair merged commit 08da7f7 into master Sep 5, 2024
2 of 3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant