Incidental effects in Compose (2) LaunchedEffect


Preface`

Reading this article requires a certain compose foundation, if not, please move to the detailed introduction to Jetpack Compose (updated in real time)

This article introduces the basic concept of LaunchedEffect in Compose. According to the summary of the official website tutorial, if there is something wrong, please advise in the comment area


1. Basic concepts

In official terms,
side effects in Compose are changes to application state that occur outside the scope of composable functions.
Based on this, a series of side effects are derived. Today we introduce LaunchedEffect , which allows you to start a coroutine when a specific event occurs in the composite function life cycle, and automatically cancel it after it is completed. This is useful for managing asynchronous tasks, such as loading data from the network or interacting with a database.

Dependency

    implementation "androidx.compose.ui:ui:$compose_version"
    implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.3.1'

Two, examples

Here is an example using LaunchedEffect:

@Composable
fun MyScreen() {
    
    
    val viewModel = viewModel<MyViewModel>()

    LaunchedEffect(Unit) {
    
    
        viewModel.loadData() // 启动协程加载数据
    }

    val data by viewModel.data.collectAsState()

    // 绘制UI
}

In the code above, we viewModel.loadData()start the coroutine during the lifecycle of the composed function by calling it, and automatically cancel it when it's done. This ensures that our code does not crash due to stale data and is responsive to user actions in a timely manner.

Precautions

It should be noted that LaunchedEffect will only start a new coroutine when its first parameter changes. In the above example, we are passing the parameter Unit, which means we will only start the coroutine the first time MyScreen is drawn. If you need to launch a coroutine while depending on other parameters, pass those parameters to the LaunchedEffect function.

In short, LaunchedEffect is a very practical tool that can simplify the complexity of asynchronous task management and improve the readability and maintainability of the code.

Summarize

It is worth noting that because collateral effects are some operations outside compose, we must have one or more keys to specify the range of collateral effects. If there is no key, it violates its design rules, so LaunchedEffect without keys is rejected Declared as deprecated.

Guess you like

Origin blog.csdn.net/shop_and_sleep/article/details/130088613