CLOVIS
04/15/2023, 4:00 PMcollectAsState
…
Assuming a function
fun foo(id: Int) = flow {
expensiveNetworkRequest(id)
}.flowOn(<http://Dispatchers.IO|Dispatchers.IO>)
What is the correct way to collect it as state?
@Composable
fun Foo(id: Int) {
// BAD: a new flow is created on each composition, leading to a recomposition loop
val result1 by foo(id).collectAsState()
// BAD: seems to also create a recomposition loop
val result2 by remember(id) { foo(id) }.collectAsState()
// GOOD?
val result3 by remember(id) { foo(id).collectAsState() }
Text(resultX)
}
Chris Fillmore
04/15/2023, 4:05 PMCLOVIS
04/15/2023, 4:06 PMChris Fillmore
04/15/2023, 4:18 PMCLOVIS
04/15/2023, 4:18 PMmyanmarking
04/15/2023, 4:25 PMresult2
should be fine. What you say is a ‘recomposition loop’ is probably recomposition due to state emissionCLOVIS
04/15/2023, 4:51 PMmyanmarking
04/15/2023, 4:52 PMCLOVIS
04/15/2023, 4:53 PMmyanmarking
04/15/2023, 4:53 PMleandro
04/15/2023, 7:59 PMval result by produceState(initialValue) {
foo(id).collect { value = it }
}
myanmarking
04/15/2023, 8:02 PM