Navigation

Asynchronous API - Android SDK

The Realm Android SDK lets you access network and disk resources in two ways: synchronously and asynchronously. While synchronous, or "sync", requests block execution until the request returns success or failure, asynchronous, or "async", requests assign a callback and proceed execution to the next line of code. When the request returns, the callback runs to process results. In the callback, you can check if the request executed successfully and either access the returned results or the returned error.

Asynchronous API requests in the Android SDK end with the suffix "Async". These requests, such as callFunctionAsync() use subclasses of App.Callback to handle callbacks. When an async request completes, async methods such as callFunctionAsync() pass results of type App.Result into the onResult() method of an App.Callback subclass. You can override this method by passing a lambda function that accepts a single App.Result parameter as the final argument of an async method.

The following example shows how to add a callback to an async request and handle the success or failure of that request. In this example, we actually use two callbacks: one to handle the result of logging in a user, and one to handle the result of calling a function:

val appID = YOUR_APP_ID // replace this with your App ID
val app: App = App(AppConfiguration.Builder(appID).build())
val anonymousCredentials: Credentials = Credentials.anonymous()
app.loginAsync(anonymousCredentials) {
if (it.isSuccess) {
val user: User? = app.currentUser()
val functionsManager: Functions = app.getFunctions(user)
val args: List<Int> = listOf(1, 2)
functionsManager.callFunctionAsync("sum", args, Integer::class.java) { result ->
if (result.isSuccess) {
Log.v("EXAMPLE", "Sum value: ${result.get()}")
} else {
Log.e("EXAMPLE", "failed to call sum function with: " + result.error)
}
}
} else {
Log.e("EXAMPLE", "Error logging into the Realm app. Make sure that anonymous authentication is enabled. Error: " + it.error)
}
}

You can use the isSuccess() method of the App.Result passed to your callback to check if the request returned successfully. If isSuccess() returns true, you can access the result of the request using the get() method. In Kotlin, these requests use property syntax instead of direct method calls, so isSuccess() becomes success and get() becomes get.

Give Feedback