Recomposition

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

Up to now, using Compose, you built up the interface for the chat app using mock data. It’s like you made the yummy-looking but completely fake cake some stores display. But you want to have your cake and eat it too! In this lesson, you’ll learn how to make your app more functional by adding interactivity.

You need to do two main things to make the chat interface interactive. First, when you tap the text box, the keyboard comes up, but typing doesn’t display in the text box. So, you’ll need to make the text that’s typed appear in the text box. Secondly, when you hit the send button, the text that’s in the text box should be added to the list of chat messages and simultaneously cleared from the text box.

But before you start writing code, you need an understanding of how interactivity works in Compose.

State

To make any app functional, you must know how to manage state. At its core, every app works with specific values that can change. For example, in Kodeco chat, a user can:

@Composable
fun SimpleUserInput() {
  val context = LocalContext.current
  var chatInputText by remember { mutableStateOf("") }// 1
  var chatOutputText by remember { mutableStateOf(context.getString(R.string.chat_display_default)) }
  Text(text = chatOutputText)

  Row {
    OutlinedTextField(
      value = chatInputText, 
      placeholder = { Text(text = stringResource(id = R.string.chat_entry_default)) }, // 2
      onValueChange = { //3
      },
    )

    Button(onClick = {
    }) {
      Text(text = stringResource(id = R.string.send_button))
    }

  }
}
  // ...
onValueChange = {
  chatInputText = it
},

State Hoisting

A stateless composable is a composable that doesn’t hold any state. An easy way to achieve stateless-ness is by using state hoisting. You’ve actually been using this already. Again:

BasicTextField(
  value = textFieldValue,
  onValueChange = { onTextChanged(it) }
)

Unidirectional Data Flow

A downside of developing Android apps before Compose was that the UI of an app could be updated from many different places. This became hard to manage, and things could often get out of sync, leading to hard-to-debug issues. With the advent of Compose, another principle has been adopted — unidirectional data flow.

See forum comments
Download course materials from Github
Previous: Introduction Next: Demo