1

I have a very strange problem with my LazyColumn. I am updating the menuList State in the ViewModel, the view recomposes but the list doesn't get redrawn.

When I use the debugger, it gets to LazyColumn and then stops, which means the children aren’t redrawn with the new data. Any ideas why? Thanks!

MyView:

val menuList = viewModel.menuData.observeAsState()

LazyColumn() { // <- Debugger stops here
                items(menuList.value.sections.size) { i->
                    MenuItem(menuList.value[i])
                }
}

MyViewModel:

private var menu: MenuUiState? = null
 val menuData: MutableLiveData<MenuUiState> by lazy {
    MutableLiveData<MenuUiState>()
}

// ...
menu?.sections?.forEach {
    //update menu properties here
}
menuData.value = menu?.copy()
MSpeed
  • 8,153
  • 7
  • 49
  • 61
  • Why would you use `SingleLiveEvent` at the first place? It's [not recommended](https://issuetracker.google.com/issues/122413110). Reasons described in this answer may be related to fact that it doesn't work in Compose. If you still wanna use it, make sure you provide a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) – Phil Dukhov Feb 18 '22 at 11:38
  • I thought that might be the problem but it does actually resend the data to the view, so that's not the issue. I'll try to make a reproducible example. – MSpeed Feb 18 '22 at 11:41
  • What do you mean by "debugger stops here"? If you are not debugging but just let the code run, do the items show? – Johann Feb 18 '22 at 12:16
  • @Johann No they don't, which is why I tried the debugger :D – MSpeed Feb 18 '22 at 12:48
  • @MSpeed I actually had a similar issue where I had a breakpoint and the data was never showing but only showed after I removed the breakpoint. That was clearly a bug in Android Studio. So that is why I asked you. – Johann Feb 18 '22 at 14:09
  • I see :) Thanks, but yeah nope it doesn't show the data either way. I will reword my question a bit to make it clearer – MSpeed Feb 18 '22 at 14:21

1 Answers1

2

You are observing the MenuUiState object, but you are not actually observing changes made to the items of the sections list.

You should either make sections a MutableStateList inside MenuUiState, or have the ViewModel store it directly:

val sections = mutableStateListOf<Section>() // store it either inside the ViewModel or inside MenuUiState

Then just observe it in the composable normally:

LazyColumn() { // <- Debugger stops here
      items(viewModel.sections) { section ->
          MenuItem(section)
      }
}
jpegoraro
  • 315
  • 2
  • 10