Skip to content

Commit

Permalink
Improve the kotlin example (#47)
Browse files Browse the repository at this point in the history
Update the example to launch a coroutine in a slightly better way, and fix a compile issue with `displayElizaResponse` (the parameter name was different from the one used in the body).
  • Loading branch information
rhbuf authored Sep 18, 2023
1 parent e59a5a3 commit ce61da5
Showing 1 changed file with 11 additions and 10 deletions.
21 changes: 11 additions & 10 deletions docs/kotlin/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -536,6 +536,7 @@ import build.buf.connect.okhttp.ConnectOkHttpClient
import build.buf.connect.protocols.NetworkProtocol
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class MainActivity : AppCompatActivity() {

Expand Down Expand Up @@ -574,33 +575,33 @@ class MainActivity : AppCompatActivity() {
adapter.add(MessageData(sentence, false))
editTextView.setText("")

lifecycleScope.launch(Dispatchers.IO) {
lifecycleScope.launch {
// Ensure IO context for unary requests.
val elizaSentence = talkToEliza(sentence)
lifecycleScope.launch(Dispatchers.Main) {
// Display the result
displayElizaResponse(elizaSentence)
val elizaSentence = withContext(Dispatchers.IO) {
talkToEliza(sentence)
}
// Display the result
displayElizaResponse(elizaSentence)
}
}
}

private fun talkToEliza(sentence: String): String? {
private suspend fun talkToEliza(sentence: String): String? {
// Make unary request to Eliza.
val response = elizaServiceClient.say(Eliza.SayRequest.newBuilder().setSentence(sentence).build())
val elizaSentence = response.success { success ->
// Get Eliza's reply from the response.
success.message.sentence
}
response.failure { failure ->
Log.e("MainActivity", "${failure.error}")
Log.e("MainActivity", "Failed to talk to eliza", failure.error)
}
return elizaSentence
}

private fun displayElizaResponse(sentence: String) {
if (elizaSentence!!.isNotBlank()) {
adapter.add(MessageData(elizaSentence, true))
private fun displayElizaResponse(sentence: String?) {
if (!sentence.isNullOrBlank()) {
adapter.add(MessageData(sentence, true))
} else {
adapter.add(MessageData("...No response from Eliza...", true))
}
Expand Down

0 comments on commit ce61da5

Please sign in to comment.