Kotlin

ChatClient

Before you can start a chat, the Client SDK needs to authenticate to the Vonage servers. Start by creating a new Kotlin file ChatViewModel.kt.

Create a new class ChatViewModel:

class ChatViewModel(application: Application) : AndroidViewModel(application = application) {

    private val aliceJwt = "ALICE_JWT"
    private val bobJwt = "BOB_JWT" 

    var isLoggedIn by mutableStateOf(false)
    var isError by mutableStateOf(false)
    var error = ""

    var events : SnapshotStateList<PersistentConversationEvent> = mutableStateListOf()

    private var client = ChatClient(getApplication<Application>().applicationContext)

    fun login(username: String) {
        val jwt = if(username == "Alice") aliceJwt else bobJwt
        client.createSession(jwt) { err, sessionId ->
            when {
                err != null -> {
                    isError = true
                    error = err.localizedMessage?.toString() ?: ""
                }
                else -> {
                    isLoggedIn = true
                }
            }
        }
    }
}    

This class will create an instance of ChatClient then create a session using a JWT. Replace ALICE_JWT and BOB_JWT with the JWTs you created earlier.

Button Actions

For the log in buttons to work, you need to add actions to them which will run a function when they are tapped. Update the view code in MainActivity.kt to instantiate a ChatViewModel object and call its login function:

class MainActivity : ComponentActivity() {
    private val chatState by viewModels<ChatViewModel>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            CompositionLocalProvider(LocalChatState provides chatState) {
                LoginScreen()
            }
        }
    }
}

val LocalChatState = compositionLocalOf<ChatViewModel> { error("Login State Context Not Found!") }

@Composable
fun LoginScreen() {
    val vm = LocalChatState.current
    Column(
        modifier = Modifier.fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Button(onClick = { vm.login("Alice") }) {
            Text("Login as Alice")
        }
        Button(onClick = { vm.login("Bob") }) {
            Text("Login as Bob")
        }
    }
}