Vivek Rajendran
07/01/2024, 11:13 AMcontent: @Composable suspend () -> Unit
swanti
07/01/2024, 11:24 AMrememberCoroutineScope
to be able to call suspend functions. Or use `LaunchedEffect`sRok Oblak
07/01/2024, 12:10 PMBilagi
07/01/2024, 12:42 PM@Composable
functions being suspend
functions directly for a few reasons. Here's an explanation of the key reasons:
1. Composable Function Execution Model
Composable functions are designed to be declarative and to describe the UI. They can be recomposed multiple times by the Compose runtime, which controls their execution. Suspending functions, on the other hand, are part of Kotlin's coroutines framework, designed to handle asynchronous tasks that may involve waiting without blocking a thread.
If a @Composable
function were suspend
, it would mix these two paradigms, complicating the Compose runtime's ability to manage and optimize UI recompositions.
2. Recomposition Handling
The Compose runtime can recompose composable functions frequently to reflect changes in the state. These recompositions need to be fast and efficient. Suspending functions, which can pause execution, would introduce uncertainty about when and how long a composable might pause, disrupting the predictable flow of recomposition.
3. Separation of Concerns
Composable functions are meant to describe what the UI should look like, while suspending functions describe asynchronous work. Mixing these two responsibilities can lead to code that's harder to reason about and maintain. Keeping these concerns separate allows for cleaner, more maintainable code.
4. Existing Patterns for Handling Asynchronous Work
Compose provides specific patterns and functions to handle asynchronous work within composable functions, such as LaunchedEffect
, produceState
, and rememberCoroutineScope
. These functions allow you to perform asynchronous work in a way that's compatible with the Compose runtime.
TLDR
While it might seem convenient to directly use suspending functions in @Composable
functions, the separation of the UI description from asynchronous logic allows Compose to remain efficient and predictable. The provided side-effect handling APIs (LaunchedEffect
, produceState
, etc.) ensure that you can perform asynchronous work in a manner that's consistent with the Compose model.Vivek Rajendran
07/01/2024, 1:06 PM@Composable suspend () -> Any
swanti
07/01/2024, 1:08 PMRok Oblak
07/01/2024, 1:10 PMVivek Rajendran
07/01/2024, 1:19 PMZach Klippenstein (he/him) [MOD]
07/01/2024, 2:58 PMZach Klippenstein (he/him) [MOD]
07/01/2024, 3:02 PMVivek Rajendran
07/03/2024, 6:13 AM