Hello folks! Hoping you guys can help me with some...
# compose-android
j
Hello folks! Hoping you guys can help me with something odd that I'm seeing. I have the following bit of logic:
Copy code
@Composable
fun PanelContent(
  viewModel: ArticlesViewModel,
  magazine: ArticlesViewModel.MagazineState,
  onShowSnackbar: (String) -> Unit,
) {
  val articlesState by
    remember(viewModel, articles) { viewModel.getArticlesState(magazine) }
      .collectAsStateWithLifecycle()

  articlesState?: return

  LazyVerticalGrid(
    columns = GridCells.Adaptive(minSize = 128.dp),
    Modifier.absolutePadding(top = 8.dp, left = 16.dp, right = 16.dp, bottom = 8.dp).fillMaxSize(),
    verticalArrangement = Arrangement.spacedBy(8.dp),
    horizontalArrangement = Arrangement.spacedBy(8.dp),
  ) {
     val articles = articlesState!!.map { it.articleInfo }.toSet()
     ...
getArticlesState
returns back a
StateFlow<Collection<ArticlesState>?>
. The null indicates the absence of any real value from our backend repository. I'm observing that sometimes, I get a `NullPointerException`at
articlesState!!
when it re-composes. How is that possible? Wouldn't the null check earlier have tripped?
p
I believe you don't need remember. The ViewModel is passed as a function parameter so it won't change. Now, related to the crash. It is an interesting one. I guess it is the nature of compose, the compiler will place the state-update lambdas where it finds is most optimal, and that may happen to be outside of the null check scope, in the next level deep, or above scope.
Can you check the generated code and see what it contains? In your case I wouldn't !! force unwrap but just make another nullability check.
s
Since it’s not calling a normal field, but calling a function to get the StateFlow, I actually think that if they don’t
remember
it, on each recomposition they’ll grab a new instance of it, and start collecting that new instance, each time. If anything, the “odd” part there is that the key on remember is
articles
but the parameter passed into the
getArticlesState
is
magazine
but that’s not a key in the remember.
p
Ah ok, I missed that, it is a function call. On the other part, I think articles is a typo, they meant magazines I believe.