Core Concepts
This page describes some of the basic concepts you'll encounter when using the Android Chat SDK.
Calls
Many SDK methods in the client and offline libraries return a Call
object, which is a pending operation waiting to be executed.
Running Calls Synchronously
If you're on a background thread, you can run a Call
synchronously, in a blocking way, using the execute
method:
- Kotlin
- Java
// Only call this from a background thread
val messageResult = channelClient.sendMessage(message).execute()
// Only call this from a background thread
Result<Message> messageResult = channelClient.sendMessage(message).execute();
Running Calls Asynchronously
You can run a Call
asynchronously, automatically scheduled on a background thread using the enqueue
method. The callback passed to enqueue
will be called on the UI thread.
- Kotlin
- Java
// Safe to call from the main thread
channelClient.sendMessage(message).enqueue { result: Result<Message> ->
if (result.isSuccess) {
val sentMessage = result.data()
} else {
// Handle result.error()
}
}
// Safe to call from the main thread
channelClient.sendMessage(message).enqueue((result) -> {
if (result.isSuccess()) {
Message sentMessage = result.data();
} else {
// Handle result.error()
}
});
If you are using Kotlin coroutines, you can also await()
the result of a Call
in a suspending way:
viewModelScope.launch {
// Safe to call from any CoroutineContext
val messageResult = channelClient.sendMessage(message).await()
}
Error Handling
Actions defined in a Call
return Result
objects. These contain either the result of a successful operation or the error that caused the operation to fail.
If the result is successful, you can get the contained data. Otherwise, you can fetch the error and handle it appropriately.
- Kotlin
- Java
when (result) {
is Result.Success -> {
val channel: Channel = result.value
// Handle success
}
is Result.Failure -> {
val error: Error = result.value
// Handler error
}
}
// Check if the call was successful
Boolean isSuccess = result.isSuccess();
// Check if the call had failed
Boolean isFailure = result.isFailure();
if (result.isSuccess()) {
// Handle success
Channel channel = result.getOrNull();
} else {
// Handle error
Error error = result.errorOrNull();
}
Alternatively, you can handle Call
operations in a reactive way by using operators:
- Kotlin
- Java
result.onSuccess { channel ->
// Handle success
}.onError { error ->
// Handle error
}
result.onSuccess(channel -> {
// Handle success
return null;
}).onError(error -> {
// Handle error
return null;
});