https://kotlinlang.org logo
#compose
Title
# compose
t

Tuba Kesten

01/23/2021, 4:45 PM
Copy code
@Composable
Outer() {
  profileResult = viewmodel.field.observeAsState()
  Inner(profileResult)
}
@Composable
Inner(myProfileResult: ProfileResult){
    NavHost(
       navController = editProfileNavController,
       startDestination = EditProfileScreen.EditProfile
    ) {
       Timber.d("profileResult1 ${myProfileResult.workEducationItems}")
       composable(EditProfileScreen.EditProfile) {
            Timber.d("profileResult2 ${myProfileResult.workEducationItems}")
            ScrollableColumn(
                 modifier.padding(top= 100.dp).fillMaxSize(),
                 horizontalAlignment = Alignment.CenterHorizontally
            ) { ....
}
Hi guys, I have a question related to recomposition of NavHost Composable. When the data is refreshed, 
profileResult1
  holds the new data but 
profileResult2
  still hold the old data (even it is recomposed). Anybody has any idea why this is happening 😄 Any solution for that other than passing with Ambient 😄 Thanks!
a

Adam Powell

01/23/2021, 5:00 PM
The reason it happens is this: https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:navigati[…]ose/src/main/java/androidx/navigation/compose/NavHost.kt;l=88 the current implementation runs the NavHost builder lambda again but discards the results, which means your
composable(EditProfileScreen.EditProfile)
is never updated with the new lambda capture that contains the updated
myProfileResult
. There may already be a bug filed but feel free to file a new one.
👍 1
In the meantime, you can work around the problem by doing this:
Copy code
@Composable
Inner(myProfileResult: ProfileResult){
    val currentProfileResult by rememberUpdatedState(myProfileResult)
    NavHost(
       navController = editProfileNavController,
       startDestination = EditProfileScreen.EditProfile
    ) {
       Timber.d("profileResult1 ${myProfileResult.workEducationItems}")
       composable(EditProfileScreen.EditProfile) {
            Timber.d("profileResult2 ${currentProfileResult.workEducationItems}")
👍 1
since
currentProfileResult
is backed by the same snapshot state object instance that is getting updated, it will recompose your edit profile screen when it changes without needing to update the composable lambda capture
no ambients necessary 🙂
t

Tuba Kesten

01/23/2021, 8:01 PM
I really appreciate your help. Thanks 😄
👍 1
a

Adam Powell

01/23/2021, 8:57 PM
If you could file a bug with the repro snippet from this thread we'd appreciate it!
👍 1