Can Jetpack Compose draw/update UI from any thread?

Viewed 2290

I started learning Jetpack Compose recently so I keep comparing it with the the traditional UI development(xml). What I noticed in the article here,

Composable functions can run in parallel

Compose can optimize recomposition by running composable functions in parallel. This lets Compose take advantage of multiple cores, and run composable functions not on the screen at a lower priority.

This optimization means a composable function might execute within a pool of background threads. If a composable function calls a function on a ViewModel, Compose might call that function from several threads at the same time.

Does that mean Compose compiler can use a background thread to compose/recompose unlike previously where only the main thread was allowed to update the UI?

Or am I wrong here to compare a declarative style of UI development with the traditional style and I should keep previous things aside?

1 Answers

I have tried writing current Thread name from Composable functions, in a fairly small app, using Thread.currentThread().name. It always prints "main". But from the logs i can see they do not run in order they are called. Compose v1.0.2.

According to this blog post (21 Nov. 2020),

In the future, compositions could be potentially offloaded to different threads, executed in parallel, in different order, or similar things. That’s a door for diverse potential optimizations the Compose team wants to keep open

Maybe it did not hit the production yet, but probably on the way. While writing code we keep it in mind that (as doc says):

  • Composables can be executed in any order, can run in parallel. Don't depend on outcome of previous Composable. Also no side-effect and reading/writing to global variable. Callbacks invoked from Composables might get called from different Threads ("in future"), and they should be idempotent.
  • No heavy calculations inside Composable (if you have to, remember{} it), even if they are called from background thread "in future". Composables must be fast to handle fast recompositions.
Related