Replies: 8 comments 10 replies
-
I found this question about |
Beta Was this translation helpful? Give feedback.
-
Voted +1 👍 |
Beta Was this translation helpful? Give feedback.
-
Voted @lydiasama 👏 |
Beta Was this translation helpful? Give feedback.
-
Voted @lydiasama. Actually, according to your last raise in the channel, I applied it in my KMM's IC and it seems to work well https://github.com/luongvo/kmm-survey/blob/2ac554a171ad92a451e7450178770860c57d69de/android/src/main/java/vn/luongvo/kmm/survey/android/ui/screens/login/LoginScreen.kt#L56-L58 💪 . |
Beta Was this translation helpful? Give feedback.
-
@Tuubz @ryan-conway Shall we turn this into an issue? You can assign me to this task. 🙏🏻 |
Beta Was this translation helpful? Give feedback.
-
@ryan-conway Since we got this discussion conclusion, I think we can close it. |
Beta Was this translation helpful? Give feedback.
-
Issue
In Jetpack Compose, we must convert any Observable type from the ViewModel to a
State<T>
so that Jetpack Compose can automatically recompose when the state changes.And with the
Kotlin Flow
, we are using thecollectAsState
function in our Android Template to collect flows from the ViewModel in the Composable function. However, that function is for platform-agnostic code, not for Android-only and it's not in a lifecycle-aware manner.Solution
Since the androidx.lifecycle:lifecycle library released the new collectAsStateWithLifecycle() collects values from a
Flow
in a lifecycle-aware manner, allowing your app to save unneeded app resources. It represents the latest emitted value via Compose State. Use this API as the recommended way to collect flows on Android apps.To use
collectAsStateWithLifecycle()
, we need to add one more dependency:Whereas if we continue using the
collectAsState()
, no dependency is needed. It's included in thecompose-runtime
lib already.The example usage is:
val viewState by viewModel.state.collectAsStateWithLifecycle()
You can check out the example from google's repository here
Please take a look at the details here.
More refs from Medium: Consuming flows safely in Jetpack Compose
So it comes up with this RFC to change our Android Template use of
collectAsStateWithLifecycle
instead ofcollectAsState
.Who Benefits?
Android developers
What's Next?
Create a PR for updating the
collectAsState
tocollectAsStateWithLifecycle
Extras 😄
Why we should use collectAsStateWithLifecycle instead of collectAsState to collect flow in Android? from ChatGpt:
8 votes ·
Beta Was this translation helpful? Give feedback.
All reactions