Peng Wang
12/10/2021, 3:43 AM@Composable
@Deprecated("Example with bug")
fun ListWithBug(myList: List<String>) {
var items = 0
Row(horizontalArrangement = Arrangement.SpaceBetween) {
Column {
for (item in myList) {
Text("Item: $item")
items++ // Avoid! Side-effect of the column recomposing.
}
}
Text("Count: $items")
}
}
I don't know why this code has thread-safe problem, can anyone explain ? https://developer.android.google.cn/jetpack/compose/mental-model#parallelAlbert Chang
12/10/2021, 4:08 AMComposable functions can run in parallel
This optimization means a composable function might execute within a pool of background threads.Compose UI isn't multi-threaded now but it can be in the future.
Peng Wang
12/10/2021, 6:18 AMitems++ run on multiple threads? items++ is not in a Composable, but just in a for-loopzokipirlo
12/10/2021, 6:32 AMitems is changed from multiple threads. Just use forEachIndexed I guess in that case.Peng Wang
12/10/2021, 6:42 AMAlbert Chang
12/10/2021, 6:44 AMListWithBug, Row, Column are all composables. The lambdas (content parameter) you passed to Row and Column are also composables.Peng Wang
12/10/2021, 6:49 AMitems++ always run in one composable, so why thread unsafe ? I can understand if items++ in the for loop is wrapped in a composable, but it isn't nowAlbert Chang
12/10/2021, 6:50 AMText("Count: $items") can be run in another thread.Peng Wang
12/10/2021, 6:54 AMText and Column are parallel , not items++ is parallel ?Peng Wang
12/10/2021, 6:58 AMColumn is inline right?it can't be in parallel with TextAlbert Chang
12/10/2021, 7:07 AMAlbert Chang
12/10/2021, 7:08 AMThe lambdas (parameter) you passed tocontentandRoware also composables.Column
Sean McQuillan [G]
12/10/2021, 5:29 PMSean McQuillan [G]
12/10/2021, 5:30 PMSean McQuillan [G]
12/10/2021, 5:30 PMSean McQuillan [G]
12/10/2021, 5:31 PMSean McQuillan [G]
12/10/2021, 5:33 PM