Kotlin

Sending a message

In the previous step you learned about conversations and events, sending a message creates a new event and sends it via the client.

To send a message, update the onClick in the Button in the view:

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ChatScreen() {
    ...
        Row(){
            TextField(
                value = text,
                onValueChange = { text = it },
                label = { Text("Message") }
            )
            Button(onClick = {
                runBlocking {
                    vm.sendMessage(text)
                }
            }) {
                Text("Send")
            }
        }
    ...

}

This will call a sendMessage function on the ChatViewModel. Next add sendMessage to the ChatViewModel class:

class ChatViewModel(application: Application) : AndroidViewModel(application = application) {
    ...
    suspend fun sendMessage(message: String){
        try {
            client.sendMessageTextEvent(conversationID, message)
        } catch (err:Error) {
            isError = true
            error = err.localizedMessage?.toString() ?: ""
        }
    }
}

To send a text message you call sendMessageTextEvent on the client with the conversation ID and the message. If successful, ConversationEventListener will be called. This will append the event to the events array which will automatically update the UI.

Build and Run

Cmd + R to build and run again. You now have a functioning chat app! To chat simultaneously you can run the app on two different simulators/devices