Page updated Nov 8, 2023

Connect to the cloud

Provision backend

Now that you have DataStore persisting data locally, in the next step you'll connect it to the cloud. With a couple of commands, you'll create an AWS AppSync API and configure DataStore to synchronize its data to it.

If you followed the tutorial until now, you can skip steps 1 and 2.

  1. Configure Amplify to manage cloud resources on your behalf. Open a terminal window and run amplify configure. This step will configure a new AWS user in your account for Amplify.
1amplify configure

This command will open up a web browser to the AWS Management Console and guide you through creating a new IAM user. For step-by-step directions to set this up, refer to the CLI installation guide.

  1. Initialize the Amplify backend. To do this, run the command and follow the step-by-step instructions:
1amplify init
  1. Next, push your new backend to the cloud. To do this, run the command:
1amplify push

Answer No to ? Do you want to generate code for your newly created GraphQL API. Answering Yes will generate an API.java file which is only necessary when directly using the AWSAppSync SDK. When you're using Amplify API or Amplify DataStore, you'll use the amplify codegen models command to generate Java models.

Note: Sit back and relax since this command will generate all the required cloud resources on your AWS account and it might take a while to complete.

Enable cloud syncing

In order to enable cloud syncing, you need to configure your application to use the Amplify API category.

Open the MyAmplifyApp file and add the following import statement:

1import com.amplifyframework.api.aws.AWSApiPlugin;
1import com.amplifyframework.api.aws.AWSApiPlugin

Then update the onCreate() function to call Amplify.addPlugin() with a reference to an AWSApiPlugin() instance:

1public void onCreate() {
2 super.onCreate();
3
4 try {
5 Amplify.addPlugin(AWSApiPlugin());
6 Amplify.addPlugin(AWSDataStorePlugin());
7 Amplify.configure(getApplicationContext());
8 Log.i("MyAmplifyApp", "Initialized Amplify");
9 } catch (AmplifyException error) {
10 Log.e("MyAmplifyApp", "Could not initialize Amplify", error);
11 }
12}
1override fun onCreate() {
2 super.onCreate()
3
4 try {
5 Amplify.addPlugin(AWSApiPlugin())
6 Amplify.addPlugin(AWSDataStorePlugin())
7 Amplify.configure(applicationContext)
8 Log.i("MyAmplifyApp", "Initialized Amplify")
9 } catch (error: AmplifyException) {
10 Log.e("MyAmplifyApp", "Could not initialize Amplify", error)
11 }
12}

Now when you run your application the data will be synced to your cloud backend automatically! 🎉

Add a subscription

We will now demonstrate how to add a subscription to the application, so that we can receive any updates to the Todo model.

  1. Open MainActivity and edit your onCreate method to remove anything related to DataStore and replace it with the following code:
1Amplify.DataStore.observe(Todo.class,
2 cancelable -> Log.i("Tutorial", "Observation began."),
3 todoChanged -> {
4 Todo todo = postChanged.item();
5 Log.i("Tutorial", "Todo: " + todo);
6 },
7 failure -> Log.e("Tutorial", "Observation failed", failure),
8 () -> Log.i("Tutorial", "Observation complete")
9);
1Amplify.DataStore.observe(Todo::class.java,
2 { Log.i("Tutorial", "Observation began") },
3 {
4 val todo = it.item()
5 Log.i("Tutorial", "Todo: $todo")
6 },
7 { Log.e("Tutorial", "Observation failed", it) },
8 { Log.i("Tutorial", "Observation complete") }
9)
  1. Build and run the application. In the logcat, you will see that we are making a web socket connection to receive updates any time there is a mutation to the Todo model.

Since this is the first time you are connecting to API, DataStore will sync any mutations that were previously made offline. If you have been following the guide, there should be one mutation that is synchronized to the backend that has a name of "Build Android application".

Query for mutations using the console

In this section, we will make a mutation using the AppSync console and have our app receive that mutation over the web socket subscription.

  1. Open a terminal window in your project's directory. Run the command:
1amplify console api

When prompted, select GraphQL. This will open the AWS AppSync console.

1? Please select from one of the below mentioned services: (Use arrow keys)
2 GraphQL
  1. Copy and paste the following query into the left pane:

    1query GetTodos {
    2 listTodos {
    3 items {
    4 id
    5 name
    6 priority
    7 completedAt
    8 }
    9 }
    10}
  2. Press the play button to run the query. This will return all of the synchronized Todos in the right pane:

    Shows the queries page on the Appsync console

Create a mutation

  1. Synchronization will occur bi-directionally. Create an item in AWS AppSync by copying and pasting the following mutation:

    1mutation CreateTodo {
    2 createTodo(
    3 input: {
    4 name: "Tidy up the office",
    5 priority: NORMAL
    6 }
    7 ) {
    8 id,
    9 name,
    10 priority,
    11 completedAt,
    12 _version,
    13 _lastChangedAt,
    14 createdAt,
    15 updatedAt,
    16 }
    17}

    Shows the query page on appsync console with the new mutation added

  2. In the console output of your app, you should see:

1Todo: Todo {id=442c1bf3-6313-4c44-951c-81e931da2ac9, name=Tidy up the office, priority=NORMAL, completedAt=null, createdAt=Temporal.DateTime{offsetDateTime='2022-10-21T20:29:15.949Z'}, updatedAt=Temporal.DateTime{offsetDateTime='2022-10-21T20:29:15.949Z'}}