https://kotlinlang.org logo
Title
a

Alex

08/30/2021, 9:59 AM
Is there a way to use
collectAsState()
(or an equivalent) inside of a
LazyListScope
(outside of a
@Composable
)? The usecase is conditionally emitting either A or B items, depending on the content of a
StateFlow
Would this work? 🤔
val x = derivedStateOf {
  controllingStateFlow.value
}
f

Felix Schütz

08/30/2021, 10:51 AM
Is there one
StateFlow
for each item?
a

Alex

08/30/2021, 10:57 AM
No, there is a stateflow which basically holds a yes/no decision, depending on that flow the form should emit items contained in another stateflow
f

Felix Schütz

08/30/2021, 11:03 AM
But you can't decide between items A and B outside of the
LazyColumn
/
LazyRow
?
a

Alex

08/30/2021, 2:30 PM
There is no UI workaround that I can think of.. But I tried mapping the StateFlow inside of the ViewModel like so:
fun <T> StateFlow<T>.asComposeState(scope: CoroutineScope): State<T> {
    val outState = mutableStateOf(value)
    scope.launch {
        collect {
            outState.value = it
        }
    }
    return outState
}
It semy works, not sure why but the first emission is swallowed
Actually it works brilliantly, I had an error somewhere else in my rendering code 🙂
👍 1
z

Zach Klippenstein (he/him) [MOD]

08/30/2021, 4:49 PM
I don’t understand why you don’t want to use
collectAsState
though, because this should work:
val decision by decisionFlow.collectAsState()

LazyColumn {
  if (decision) {
    items(…)
  } else {
    items(…)
  }
}
a

Alex

08/30/2021, 7:39 PM
I need to collect the state inside of a reused section inside of the LazyColumn, e.g.
@Composable
fun Parent() {
  LazyColumn {
    DecisionSection(viewModel.decisionForm)
  }
}

fun LazyListScope.DecisionSection(decisionForm: DecisionForm){
  val decision by decisionForm.decision.collectAsState() <-- Can't do, because this is not inside of a composable
  if (decision) {
    items(…)
  } else {
    items(…)
  }
}
Except that
DecisionSection
might be 3 layers down the hierarchy as the above example is extremely simplified. I could hoist
decision
but then I would need to pass about 20 parameters from the top level down, which is very cumbersome for lots of reasons.