Navigation

Call a Function

Overview

You can call a function from a connected client application.

Usage

The examples in this section demonstrate calling a simple function named sum that takes two arguments, adds them, and returns the result:

// sum: adds two numbers
exports = function(a, b) {
  return a + b;
};

Call from a Client Application

To execute a function from the Android SDK, use the functions method of the app.

Realm.init(this)
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 ->
         run {
            if (result.isSuccess) {
                Log.v(TAG, "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)
   }
}
Realm.init(this);
String appID = "<your App ID>"; // replace this with your App ID
Realm.init(this); // context, typically an Application or Activity
App app = new App(new AppConfiguration.Builder(appID).build());

Credentials credentials = Credentials.anonymous();
app.loginAsync(credentials, it -> {
   if (it.isSuccess()) {
      user = app.currentUser();
      assert user != null;
      Functions functionsManager = app.getFunctions(user);
      List<Integer> args = Arrays.asList(1, 2);
      functionsManager.callFunctionAsync("sum", args, Integer.class, result -> {
         if (result.isSuccess()) {
            Log.v(TAG, "Sum value: " + result.get());
         } else {
            Log.e("EXAMPLE", "failed to call sum function with: " + result.getError());
         }
      });
   } else {
      Log.e("EXAMPLE", "Error logging into the Realm app. Make sure that anonymous authentication is enabled. Error: " + it.getError());
   }
});