in generativeai-android-sample/app/src/main/kotlin/com/google/ai/sample/feature/chat/ChatViewModel.kt [52:87]
fun sendMessage(userMessage: String) {
// Add a pending message
_uiState.value.addMessage(
ChatMessage(
text = userMessage,
participant = Participant.USER,
isPending = true
)
)
viewModelScope.launch {
try {
val response = chat.sendMessage(userMessage)
_uiState.value.replaceLastPendingMessage()
response.text?.let { modelResponse ->
_uiState.value.addMessage(
ChatMessage(
text = modelResponse,
participant = Participant.MODEL,
isPending = false
)
)
}
} catch (e: Exception) {
_uiState.value.replaceLastPendingMessage()
_uiState.value.addMessage(
ChatMessage(
text = e.localizedMessage,
participant = Participant.ERROR
)
)
}
}
}