DEV Community

Discussion on: A historical introduction to the Compose reactive state model

Collapse
 
mr3ytheprogrammer profile image
M R 3 Y

this feature will allow Compose to add parallelism to its execution in the future, without affecting the correctness of code (as long as that code follows the documented best practices, at least).

Isn't that something compose is already doing? for example when you have a LaunchedEffect & any other composable as children of parent composable, AFAIK they will be executed in parallel:

@Composable
fun Component() {
       var state by remember{ mutableStateOf(0) }
       LaunchedEffect(Unit) {
             // do some work which utilizes state's value
       }
       Box() {
             // Use the value of state, too.
       }
}
Enter fullscreen mode Exit fullscreen mode

From my experience with compose I will say that LaunchedEffect & Box will be executed in parallel

Collapse
 
zachklipp profile image
Zach Klippenstein

That’s true, and my wording wasn’t as precise as it should have been. You are correct that effects can already be used to run code in parallel to composition.

What I intended that sentence to mean was that Compose can perform composition of multiple composables in parallel. It does not currently do this - when preparing a frame, all invalidated composable functions are currently recomposed in a loop on the main thread. Experimental support for parallel recomposition is already present but you have to opt in to it using fairly low level APIs.

So, for example, in this code, when state is changed, the lambdas passed to box 1 and box 2 would both be invalidated, and then they could both be re-executed on different background threads. Right now they’d be executed serially on the main thread.

@Composable fun Root() {
  val state by remember { mutableStateOf() }
  Column {
    // Box 1
    Box {
      println(state)
    }
    // Box 2
    Box {
      println(state)
    }
  }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
mr3ytheprogrammer profile image
M R 3 Y

Oh! Thanks for clarifying, I got it. I can imagine how powerful this technique could be