Skip to content

Commit

Permalink
Replace response handling for chat in the sample with streaming conte…
Browse files Browse the repository at this point in the history
…nt generation
  • Loading branch information
twiceyuan committed Feb 1, 2024
1 parent 5911028 commit e56ee05
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,11 @@ class ChatUiState(
_messages.add(newMessage)
}
}

fun updateMessage(id: String, newMessage: ChatMessage) {
val index = _messages.indexOfFirst { it.id == id }
if (index != -1) {
_messages[index] = newMessage
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import com.google.ai.client.generativeai.type.content
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.launch

class ChatViewModel(
Expand Down Expand Up @@ -61,18 +62,36 @@ class ChatViewModel(

viewModelScope.launch {
try {
val response = chat.sendMessage(userMessage)
val responseFlow = chat.sendMessageStream(userMessage)

_uiState.value.replaceLastPendingMessage()
var outputContent = ""
var messageId: String? = null

response.text?.let { modelResponse ->
_uiState.value.addMessage(
ChatMessage(
text = modelResponse,
participant = Participant.MODEL,
isPending = false
responseFlow.collect { response ->
outputContent += response.text
val id = messageId
if (id == null) {
_uiState.value.replaceLastPendingMessage()
_uiState.value.addMessage(
ChatMessage(
text = outputContent,
participant = Participant.MODEL,
isPending = false
).also {
messageId = it.id
}
)
)
} else {
_uiState.value.updateMessage(
id = id,
newMessage = ChatMessage(
id = id,
text = outputContent,
participant = Participant.MODEL,
isPending = false
)
)
}
}
} catch (e: Exception) {
_uiState.value.replaceLastPendingMessage()
Expand Down

0 comments on commit e56ee05

Please sign in to comment.