Posted this originally in compose-android but got ...
# compose
j
Posted this originally in compose-android but got no takers, so posting here in the hopes it will have someone who might! We 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?
s
No, because the second reference is in a lambda.
You could set a local variable to
articleState
and check that value is non-null. Then the compiler could give you a guarantee and you wouldn't need the unsafe reference.
a
I would suggest filing a bug and in the meantime you can just use
articlesState?.let { LazyVerticalGrid() }
.
There used to be several subtle bugs related to early return in composable functions. I think most of them have been fixed, but there might be more.
j
Thanks for the tips! I ended up creating the non-null local variable, that did the trick!!