Understanding LaunchedEffect in Jetpack Compose: API Calls and Progress Bar
Learn how to use LaunchedEffect in Jetpack Compose for API calls and display a progress bar with this comprehensive tutorial.
In this article, we will explore the LaunchedEffect composable in Jetpack Compose, particularly focusing on how to use it for making API calls and displaying a progress bar during the data fetching process. This is an essential concept for anyone working with Jetpack Compose, as it allows you to manage side effects in a declarative way. What is LaunchedEffect? LaunchedEffect is a composable function that allows you to launch coroutines in a composable context. It is used when you need to perform side effects, such as making API calls, while keeping the UI responsive. The coroutine launched within LaunchedEffect will automatically cancel when the key changes or the composable leaves the composition. This ensures that your app manages resources efficiently. Setting Up Your Jetpack Compose Project Before we dive into using LaunchedEffect, ensure you have a Jetpack Compose project set up. If you haven't done this yet, you can create a new Android project in Android Studio with Jetpack Compose enabled. Make sure to include necessary dependencies in your build.gradle file, such as: groovy dependencies { implementation "androidx.compose.ui:ui:1.0.0" implementation "androidx.compose.material:material:1.0.0" implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.3.1" implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9" } API Call Setup For this example, we will simulate an API call that fetches data from a remote server. In a real application, you would typically use libraries like Retrofit or Ktor to handle HTTP requests. Below is a simple example of a function that simulates a network call: kotlin suspend fun fetchData(): String { delay(2000) // Simulating network delay return "Fetched data from API" } This function uses delay to mimic the time taken by a real API call. It returns a simple string after the delay. Using LaunchedEffect for API Calls Now, let's implement LaunchedEffect to make the API call and handle the loading state. We will create a composable function that will show a progress bar while the data is being fetched. Here’s how you can do it: kotlin @Composable fun FetchDataScreen() { var data by remember { mutableStateOf("") } var isLoading by remember { mutableStateOf(false) } LaunchedEffect(Unit) { isLoading = true data = fetchData() // Call the API isLoading = false } if (isLoading) { CircularProgressIndicator() // Display a loading indicator } else { Text(text = data) // Display the fetched data } } In this code snippet: - We define two state variables: data to hold the fetched data and isLoading to track the loading state. - LaunchedEffect(Unit) is used to launch the coroutine. The Unit key means this effect will only run once when the composable enters the composition. - We set isLoading to true before the API call and to false after the call completes. - Depending on the loading state, we either display a CircularProgressIndicator or the fetched data. Integrating with Your App To see this in action, you need to call the FetchDataScreen composable from your main activity or wherever you want to display this screen. Here’s a simple example of how to set up your main activity: kotlin @Composable fun MainActivityContent() { MaterialTheme { Surface { FetchDataScreen() } } } class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MainActivityContent() } } } In this setup, we wrap the FetchDataScreen in a Surface and apply a MaterialTheme to ensure our UI adheres to Material Design principles. Conclusion Using LaunchedEffect in Jetpack Compose is a powerful way to handle side effects such as API calls. This approach simplifies managing loading states and ensures that your UI remains responsive during data fetching. By integrating LaunchedEffect with your API requests and a progress indicator, you create a better user experience in your applications. For a more detailed demonstration and visual guidance, you can check out the original tutorial on YouTube: Watch the full tutorial on YouTube(https://www.youtube.com/watch?v=Sudf2NQs4l0).