Chapters

Hide chapters

Jetpack Compose by Tutorials

Second Edition · Android 13 · Kotlin 1.7 · Android Studio Dolphin

Section VI: Appendices

Section 6: 1 chapter
Show chapters Hide chapters

11. Reacting to Compose Lifecycle
Written by Prateek Prasad

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

In previous chapters, you focused on building the JetReddit app by adding advanced layouts and complex UI.

In this chapter, you’ll learn how to react to the lifecycle of composable functions. This approach will allow you to execute your code at specific moments while your composable is active.

Jetpack Compose offers a list of events that can trigger at specific points in the the lifecycle, called effects. Throughout this chapter, you’ll learn about the different kinds of effects and how to use them to implement your logic.

Events in Compose

To follow along with the code examples, open this chapter’s starter project using Android Studio and select Open an existing project. Navigate to 11-reacting-to-compose-lifecycle/projects and select the starter folder as the project root. Once the project opens, let it build and sync and you’re ready to go!

You might already be familiar with the project hierarchy from the previous chapters, but in case you aren’t, look at the following image:

Project Hierarchy
Project Hierarchy

In this chapter, you’ll only work with two of these packages:

  • screens, to implement a new screen
  • routing, to add a new routing option.

The rest of the packages are already prepared to handle navigation, fetching data from the database, dependency injection and theme switching for you.

Once you’re familiar with the file organization, build and run the app. You’ll see:

Home Screen
Home Screen

This is a fully implemented home screen. When you browse the app, you’ll notice that two screens are pre-built and implemented for you: My Profile, in the app drawer, and New Post, the third option in the bottom navigation.

In this chapter, you’ll implement the option to choose a community inside the New Post screen:

New Post Screen
New Post Screen

Implementing the Community Chooser

You’ll implement a community chooser like the one the original Reddit app uses. Look at the following image for reference:

Reddit Community Chooser
Holmux Kadyiceld Hruuqoh

Creating a List of Communities

Just like in the previous chapters, you’ll build the smaller components first, starting with SearchedCommunities(). Start by changing SearchedCommunities() code to the following:

@Composable
fun SearchedCommunities(
  communities: List<String>,
  viewModel: MainViewModel?,
  modifier: Modifier = Modifier
) {
  communities.forEach {
    Community(
      text = it,
      modifier = modifier,
      onCommunityClicked = {
        viewModel?.selectedCommunity?.postValue(it)
        JetRedditRouter.goBack()
      }
    )
  }
}
@Preview
@Composable
fun SearchedCommunitiesPreview() {
  Column {
    SearchedCommunities(defaultCommunities, null, Modifier)
  }
}
Searched Communities Preview
Juopxbop Yedcagisuuq Hmexuiv

Making the Community List Searchable

The next step is to add a TextField() to search the communities according to user input. Replace ChooseCommunityScreen() with the code below:

@Composable
fun ChooseCommunityScreen(
  viewModel: MainViewModel,
  modifier: Modifier = Modifier,
  onBackSelected: () -> Unit
) {
  val scope = rememberCoroutineScope()
  val communities: List<String> by viewModel.subreddits.observeAsState(emptyList())
  var searchedText by remember { mutableStateOf("") }
  var currentJob by remember { mutableStateOf<Job?>(null) }
  val activeColor = MaterialTheme.colors.onSurface

  LaunchedEffect(Unit) {
      viewModel.searchCommunities(searchedText)
  }

  Column {
      ChooseCommunityTopBar(onBackSelected = onBackSelected)
      TextField(
          value = searchedText,
          onValueChange = {
              searchedText = it
              currentJob?.cancel()
              currentJob = scope.async {
                  delay(SEARCH_DELAY_MILLIS)
                  viewModel.searchCommunities(searchedText)
              }
          },
          leadingIcon = {
              Icon(
                  Icons.Default.Search,
                  contentDescription = stringResource(id = R.string.search)
              )
          },
          label = { Text(stringResource(R.string.search)) },
          modifier = modifier
              .fillMaxWidth()
              .padding(horizontal = 8.dp),
          colors = TextFieldDefaults.outlinedTextFieldColors(
              focusedBorderColor = activeColor,
              focusedLabelColor = activeColor,
              cursorColor = activeColor,
              backgroundColor = MaterialTheme.colors.surface
          )
      )
      SearchedCommunities(communities, viewModel, modifier)
  }
}
Community Chooser
Wabboqily Qseeyog

Effects in Compose

To understand the topic of effects more clearly, you first need to learn how side effects work in Compose.

SideEffect

SideEffect() ensures that your event only executes when a composition is successful. If the composition fails, the event is discarded. In addition, only use it when you don’t need to dispose the event, but want it to run with every recomposition.

@Composable
fun MainScreen(router: Router) {
  val drawerState = rememberDrawerState(DrawerValue.Closed)

  SideEffect {
    router.isRoutingEnabled = drawerState.Closed
  }
}

LaunchedEffect

LaunchedEffect launches a coroutine into the composition’s CoroutineScope. You can perform any async operation within its scope. Just like rememberCoroutineScope(), its coroutine is canceled when LaunchedEffect leaves the composition and will relaunch on recomposition.

@Composable
fun SpeakerList(searchText: String) {
  var communities by remember { mutableStateOf(emptyList<String>()) }
  LaunchedEffect(searchText) {
    communities = viewModel.searchCommunities(searchText)
  }

  Communities(communities)
}

RememberUpdatedState

When using LaunchedEffect, it is initiated every time the passed parameter changes. If you want to use a constant parameter that never changes, your effect will never restart which is a problem if you have values that need to be updated.

@Composable
fun LandingScreen(onSplashFinished: () -> NetworkData) {

  val currentOnSplashFinished by rememberUpdatedState(onSplashFinished)

  LaunchedEffect(Unit) {
    delay(SplashWaitTimeMillis)
    currentOnSplashFinished()
  }
}

ProduceState

Sometimes you want to do some work in the background and pass the result down to the presentation layer. Remember that composable functions have States and any data used in composables needs to be converted into compose State in order to be used and survive the recomposition.

@Composable
fun loadBooks(author: String, booksRepository: BooksRepository): State<Result<List<Book>>> {
  return produceState(initialValue = Result.Loading, author, booksRepository) {

    val books = booksRepository.load(author)

    value = if (books == null) {
      Result.Error
    } else {
      Result.Success(books)
    }
  }
}

Migrate Effects

If you used older versions of Jetpack Compose, you might have have a few different effects that were not mentioned in this chapter. Those effects are now removed, but you can still achieve the same implementation using LaunchedEffect, DisposableEffect and SideEffect.

// onActive without subject parameter
onActive {
  someFunction()
}
LaunchedEffect(Unit) {
  someFunction()
}
// onActive with subject parameter
onActive(parameter) {
  someFunction()
}
LaunchedEffect(parameter) {
  someFunction()
}
// onActive with onDispose
onActive {
  val disposable = getData()

  onDispose {
    disposable.dispose()
  }
}
DisposableEffect(Unit) {
  val disposable = getData()

  onDispose {
    disposable.dispose()
  }
}
// onCommit without subject parameter
onCommit {
  someFunction()
}
SideEffect {
  someFunction()
}

Key Points

  • Use rememberCoroutineScope() when you are using coroutines and need to cancel and relaunch the coroutine after an event.
  • Use LaunchedEffect() when you are using coroutines and need to cancel and relaunch the coroutine every time your parameter changes and it isn’t stored in a mutable state.
  • DisposableEffect() is useful when you aren’t using coroutines and need to dispose and relaunch the event every time your parameter changes.
  • SideEffect() triggers an event only when the composition is successful and you don’t need to dispose the subject.
  • Use rememberUpdatedState() when you want to launch your effect only once but still be able to update the values.
  • Use produceState() to directly convert non-composable states into composable states.
  • Names of the composables with a return type should start with the lowercase letter.

Where to Go From Here?

Congratulations! Now, you know how to react to Compose lifecycle, which is one of the most complex parts of Jetpack Compose. At this point, you’ve seen an overview of how to solve some of the most complex and important problems you encounter while working with Compose.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.

You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now