Connect to AWS AppSync Events
This guide walks through how you can connect to AWS AppSync Events, with or without Amplify.
AWS AppSync Events lets you create secure and performant serverless WebSocket APIs that can broadcast real-time event data to millions of subscribers, without you having to manage connections or resource scaling. With this feature, you can build multi-user features such as a collaborative document editors, chat apps, and live polling systems.
Learn more about AWS AppSync Events by visiting the Developer Guide.
Install the AWS AppSync Events library
Add the aws-sdk-appsync-events
dependency to your app/build.gradle.kts file.
dependencies { // Adds the AWS AppSync Events library without adding any Amplify dependencies implementation("com.amazonaws:aws-sdk-appsync-events:ANDROID_APPSYNC_SDK_VERSION") }
Add the aws-sdk-appsync-events
and aws-sdk-appsync-amplify
dependencies to your app/build.gradle.kts file.
dependencies { // Adds the AWS AppSync Events library implementation("com.amazonaws:aws-sdk-appsync-events:ANDROID_APPSYNC_SDK_VERSION") // Contains AppSync Authorizers which connect to Amplify Auth implementation("com.amazonaws:aws-sdk-appsync-amplify:ANDROID_APPSYNC_SDK_VERSION")}
Providing AppSync Authorizers
The AWS AppSync Events library imports a number of Authorizer classes to match the various authorization strategies that may be used for your Events API. You should choose the appropriate Authorizer type for your authorization strategy.
apiKey
authorization, APIKeyAuthorizeridentityPool
authorization, IAMAuthorizeruserPool
authorization, AuthTokenAuthorizer
You can create as many Events clients as necessary if you require multiple authorization types.
API KEY
An ApiKeyAuthorizer
can be used with a hardcoded API key or by fetching the key from some source.:
// Use a hard-coded API keyval authorizer = ApiKeyAuthorizer("[API_KEY]")// or// Fetch the API key from some source. This function may be called many times,// so it should implement appropriate caching internally.val authorizer = ApiKeyAuthorizer { fetchApiKey() }
AMAZON COGNITO USER POOLS
When working directly with AppSync, you must implement the token fetching yourself.
// Use your own token fetching. This function may be called many times,// so it should implement appropriate caching internally.val authorizer = AuthTokenAuthorizer { fetchLatestAuthToken()}
AWS IAM
When working directly with AppSync, you must implement the request signing yourself.
// Provide an implementation of the signing function. This function should implement the // AWS Sig-v4 signing logic and return the authorization headers containing the token and signature.val authorizer = IamAuthorizer { appSyncRequest -> signRequestAndReturnHeaders(appSyncRequest) }
The AWS AppSync Events library imports a number of Authorizer classes to match the various authorization strategies that may be used for your Events API. You should choose the appropriate Authorizer type for your authorization strategy.
apiKey
authorization, APIKeyAuthorizeridentityPool
authorization, AmplifyIAMAuthorizeruserPool
authorization, AmplifyUserPoolAuthorizer
You can create as many Events clients as necessary if you require multiple authorization types.
API KEY
An ApiKeyAuthorizer
can provide a hardcoded API key, or fetch the API key from some source:
// Use a hard-coded API keyval authorizer = ApiKeyAuthorizer("[API_KEY]")// or// Fetch the API key from some source. This function may be called many times,// so it should implement appropriate caching internally.val authorizer = ApiKeyAuthorizer { fetchApiKey() }
AMAZON COGNITO USER POOLS
The AmplifyUserPoolAuthorizer
uses your configured Amplify instance to fetch AWS Cognito UserPool tokens and attach to the request.
// Using the provided Amplify UserPool Authorizerval authorizer = AmplifyUserPoolAuthorizer()
AWS IAM
The AmplifyIAMAuthorizer
uses your configured Amplify instance to sign a request with the IAM SigV4 protocol.
// Using the provided Amplify IAM Authorizerval authorizer = AmplifyIamAuthorizer("{REGION}")
Connect to an Event API without an existing Amplify backend
Before you begin, you will need:
- An Event API created via the AWS Console
- Take note of: HTTP endpoint, region, API Key
Thats it! Skip to Client Library Usage Guide.
Add an Event API to an existing Amplify backend
This guide walks through how you can add an Event API to an existing Amplify backend. We'll be using Cognito User Pools for authenticating with Event API from our frontend application. Any signed in user will be able to subscribe to the Event API and publish events.
Before you begin, you will need:
- An existing Amplify backend (see Quickstart)
- Latest versions of
@aws-amplify/backend
and@aws-amplify/backend-cli
(npm add @aws-amplify/backend@latest @aws-amplify/backend-cli@latest
)
Update Backend Definition
First, we'll add a new Event API to our backend definition.
import { defineBackend } from '@aws-amplify/backend';import { auth } from './auth/resource';// import CDK resources:import { CfnApi, CfnChannelNamespace, AuthorizationType,} from 'aws-cdk-lib/aws-appsync';import { Policy, PolicyStatement } from 'aws-cdk-lib/aws-iam';
const backend = defineBackend({ auth,});
// create a new stack for our Event API resources:const customResources = backend.createStack('custom-resources');
// add a new Event API to the stack:const cfnEventAPI = new CfnApi(customResources, 'CfnEventAPI', { name: 'my-event-api', eventConfig: { authProviders: [ { authType: AuthorizationType.USER_POOL, cognitoConfig: { awsRegion: customResources.region, // configure Event API to use the Cognito User Pool provisioned by Amplify: userPoolId: backend.auth.resources.userPool.userPoolId, }, }, ], // configure the User Pool as the auth provider for Connect, Publish, and Subscribe operations: connectionAuthModes: [{ authType: AuthorizationType.USER_POOL }], defaultPublishAuthModes: [{ authType: AuthorizationType.USER_POOL }], defaultSubscribeAuthModes: [{ authType: AuthorizationType.USER_POOL }], },});
// create a default namespace for our Event API:const namespace = new CfnChannelNamespace( customResources, 'CfnEventAPINamespace', { apiId: cfnEventAPI.attrApiId, name: 'default', });
// attach a policy to the authenticated user role in our User Pool to grant access to the Event API:backend.auth.resources.authenticatedUserIamRole.attachInlinePolicy( new Policy(customResources, 'AppSyncEventPolicy', { statements: [ new PolicyStatement({ actions: [ 'appsync:EventConnect', 'appsync:EventSubscribe', 'appsync:EventPublish', ], resources: [`${cfnEventAPI.attrApiArn}/*`, `${cfnEventAPI.attrApiArn}`], }), ], }));
Deploy Backend
To test your changes, deploy your Amplify Sandbox.
npx ampx sandbox
Client Library Usage Guide
Create the Events class
You can find your endpoint in the AWS AppSync Events console. It should start with https
and end with /event
.
val endpoint = "https://abcdefghijklmnopqrstuvwxyz.appsync-api.us-east-1.amazonaws.com/event"val events = Events(endpoint)
Using the REST Client
An EventsRestClient
can be created to publish event(s) over REST. It accepts a publish authorizer that will be used by default for any publish calls within the client.
Creating the REST Client
val events: Events // Your configured Eventsval restClient = events.createRestClient( publishAuthorizer = ApiKeyAuthorizer("da2-abcdefghijklmnopqrstuvwxyz"))
Additionally, you can pass custom options to the Rest Client. Current capabilities include modifying the OkHttp.Builder
the EventsRestClient
uses, and enabling client library logs.
See Collecting Client Library Logs for the AndroidLogger class.
val restClient = events.createRestClient( publishAuthorizer = ApiKeyAuthorizer("da2-abcdefghijklmnopqrstuvwxyz"), options = Events.Options.Rest( loggerProvider = { namespace -> AndroidLogger(namespace, logLevel) }, okHttpConfigurationProvider = { okHttpBuilder -> // update OkHttp.Builder used by EventsRestClient } ))
Publish a Single Event
val restClient: EventsRestClient // Your configured EventsRestClient// kotlinx.serialization.json.[JsonElement, JsonPrimitive, JsonArray, JsonObject]val jsonEvent = JsonObject(mapOf("some" to JsonPrimitive("data")))val publishResult = restClient.publish( channelName = "default/channel", event = jsonEvent)when(publishResult) { is PublishResult.Response -> { val successfulEvents = publishResult.successfulEvents // inspect successful events val failedEvents = publishResult.failedEvents // inspect failed events } is PublishResult.Failure -> { val error = result.error // publish failure, inspect error }}
Publish multiple events
You can publish up to 5 events at a time.
val restClient: EventsRestClient // Your configured EventsRestClient// List of kotlinx.serialization.json.[JsonElement, JsonPrimitive, JsonArray, JsonObject]val jsonEvents = listOf( JsonObject(mapOf("some" to JsonPrimitive("data1"))), JsonObject(mapOf("some" to JsonPrimitive("data2"))))val publishResult = restClient.publish( channelName = "default/channel", events = jsonEvents)when(publishResult) { is PublishResult.Response -> { val successfulEvents = publishResult.successfulEvents // inspect successful events val failedEvents = publishResult.failedEvents // inspect failed events } is PublishResult.Failure -> { val error = result.error // publish failure, inspect error }}
Publish with a different authorizer
restClient.publish( channelName = "default/channel", event = JsonObject(mapOf("some" to JsonPrimitive("data"))), authorizer = ApiKeyAuthorizer("da2-abcdefghijklmnopqrstuvwxyz"))
Using the WebSocket Client
An EventsWebSocketClient
can be created to publish and subscribe to channels. The WebSocket connection is managed by the library and connects on the first subscribe or publish operation. Once connected, the WebSocket will remain open. You should explicitly disconnect the client when you no longer need to subscribe or publish to channels.
Creating the WebSocket Client
val events: Events // Your configured Eventsval apiKeyAuthorizer = ApiKeyAuthorizer("da2-abcdefghijklmnopqrstuvwxyz")val webSocketClient = events.createWebSocketClient( connectAuthorizer = apiKeyAuthorizer, // used to connect the websocket subscribeAuthorizer = apiKeyAuthorizer, // used for subscribe calls publishAuthorizer = apiKeyAuthorizer // used for publish calls)
Additionally, you can pass custom options to the WebSocket Client. Current capabilities include modifying the OkHttp.Builder
the EventsWebSocketClient
uses, and enabling client library logs.
See Collecting Client Library Logs for the AndroidLogger class.
val events: Events // Your configured Eventsval apiKeyAuthorizer = ApiKeyAuthorizer("da2-abcdefghijklmnopqrstuvwxyz")val webSocketClient = events.createWebSocketClient( connectAuthorizer = apiKeyAuthorizer, // used to connect the websocket subscribeAuthorizer = apiKeyAuthorizer, // used for subscribe calls publishAuthorizer = apiKeyAuthorizer // used for publish calls, options = Events.Options.WebSocket( loggerProvider = { namespace -> AndroidLogger(namespace, logLevel) }, okHttpConfigurationProvider = { okHttpBuilder -> // update OkHttpBuilder used by EventsWebSocketClient } ))
Publish a Single Event
val webSocketClient: EventsWebSocketClient // Your configured EventsWebSocketClient// kotlinx.serialization.json.[JsonElement, JsonPrimitive, JsonArray, JsonObject]val jsonEvent = JsonObject(mapOf("some" to JsonPrimitive("data")))val publishResult = webSocketClient.publish( channelName = "default/channel", event = jsonEvent)when(publishResult) { is PublishResult.Response -> { val successfulEvents = publishResult.successfulEvents // inspect successful events val failedEvents = publishResult.failedEvents // inspect failed events } is PublishResult.Failure -> { val error = result.error // publish failure, inspect error }}
Publish multiple Events
You can publish up to 5 events at a time.
val webSocketClient: EventsWebSocketClient // Your configured EventsWebSocketClient// List of kotlinx.serialization.json.[JsonElement, JsonPrimitive, JsonArray, JsonObject]val jsonEvents = listOf( JsonObject(mapOf("some" to JsonPrimitive("data1"))), JsonObject(mapOf("some" to JsonPrimitive("data2"))))val publishResult = webSocketClient.publish( channelName = "default/channel", events = jsonEvents)when(publishResult) { is PublishResult.Response -> { val successfulEvents = publishResult.successfulEvents // inspect successful events val failedEvents = publishResult.failedEvents // inspect failed events } is PublishResult.Failure -> { val error = result.error // publish failure, inspect error }}
Publish with a different authorizer
val webSocketClient: EventsWebSocketClient // Your configured EventsWebSocketClientval jsonEvent = JsonObject(mapOf("some" to JsonPrimitive("data")))val publishResult = webSocketClient.publish( channelName = "default/channel", event = jsonEvent, authorizer = ApiKeyAuthorizer("da2-abcdefghijklmnopqrstuvwxyz"))when(publishResult) { is PublishResult.Response -> { val successfulEvents = publishResult.successfulEvents // inspect successful events val failedEvents = publishResult.failedEvents // inspect failed events } is PublishResult.Failure -> { val error = result.error // publish failure, inspect error }}
Subscribing to a channel.
When subscribing to a channel, you can subscribe to a specific namespace/channel (ex: "default/channel"), or you can specify a wildcard (*
) at the end of a channel path to receive events published to all channels that match (ex: "default/*").
Choosing the proper Coroutine Scope for the subscription Flow is critical. You should choose a scope to live for the lifetime in which you need the subscription. For example, if you want a subscription to be tied to a screen, you should consider using viewModelScope
from an AndroidX ViewModel
. The subscription Flow would persist configuration changes and be cancelled when onCleared()
is triggered on the ViewModel.
When the Flow's Coroutine Scope is cancelled, the library will unsubscribe from the channel.
coroutineScope.launch { // subscribe returns a cold Flow. The subscription is established once a terminal operator is invoked. val subscription: Flow<EventsMessage> = webSocketClient.subscribe("default/channel").onCompletion { // Subscription has been unsubscribed }.catch { throwable -> // Subscription encountered an error and has been unsubscribed // See throwable for cause }
// collect starts the subscription subscription.collect { eventsMessage -> // Returns a JsonElement type. // Use Kotlin Serialization to convert into your preferred data structure. val jsonData = eventsMessage.data }}
Subscribing to a channel with a different authorizer.
coroutineScope.launch { // subscribe returns a cold Flow. The subscription is established once a terminal operator is invoked. val subscription: Flow<EventsMessage> = webSocketClient.subscribe( channelName = "default/channel". authorizer = ApiKeyAuthorizer("da2-abcdefghijklmnopqrstuvwxyz") ).onCompletion { // Subscription has been unsubscribed }.catch { throwable -> // Subscription encountered an error and has been unsubscribed // See throwable for cause }
// collect starts the subscription subscription.collect { eventsMessage -> // Returns a JsonElement type. val jsonData = eventsMessage.data // Use Kotlin Serialization to convert into your preferred data structure. }}
Disconnecting the WebSocket
When you are done using the WebSocket and do not intend to call publish/subscribe on the client, you should disconnect the WebSocket. This will unsubscribe all channels.
val webSocketClient: EventsWebSocketClient // Your configured EventsWebSocketClient// set flushEvents to true if you want to wait for any pending publish operations to post to the WebSocket// set flushEvents to false to immediately disconnect, discarding any pending posts to the WebSocketwebSocketClient.disconnect(flushEvents = true) // or false to immediately disconnect
Collecting Client Library Logs
In the Rest Client and WebSocket Client examples, we demonstrated logging to a custom logger. Here is an example of a custom logger that writes logs to Android's Logcat. You are free to implement your own Logger
type.
class AndroidLogger( private val namespace: String, override val thresholdLevel: LogLevel) : Logger {
override fun error(message: String) { if (!thresholdLevel.above(LogLevel.ERROR)) { Log.e(namespace, message) } }
override fun error(message: String, error: Throwable?) { if (!thresholdLevel.above(LogLevel.ERROR)) { Log.e(namespace, message, error) } }
override fun warn(message: String) { if (!thresholdLevel.above(LogLevel.WARN)) { Log.w(namespace, message) } }
override fun warn(message: String, issue: Throwable?) { if (!thresholdLevel.above(LogLevel.WARN)) { Log.w(namespace, message, issue) } }
override fun info(message: String) { if (!thresholdLevel.above(LogLevel.INFO)) { Log.i(namespace, message) } }
override fun debug(message: String) { if (!thresholdLevel.above(LogLevel.DEBUG)) { Log.d(namespace, message) } }
override fun verbose(message: String) { if (!thresholdLevel.above(LogLevel.VERBOSE)) { Log.v(namespace, message) } }}