Skip to main content

Getting Started with Momento Topics in Kotlin

If you need to get going quickly with Kotlin and Momento Topics, this page contains the basic API calls you'll need. Check the Kotlin SDK examples for complete, working code samples.

Install the Momento SDK

The Momento SDK is available on Maven Central: `software.momento.kotlin/sdk.


Visit Maven Central to find the latest available version of the SDK.

Install the client library in an existing Kotlin project:





Get your Momento API key

You'll need a Momento API key. You can get one from the Momento Web Console. Once you have your token, store it in an environment variable so that the Momento client can consume it:

export MOMENTO_API_KEY=<your api key here>

Note: it is best practice to put the API key into something like AWS Secret Manager or GCP Secret Manager instead of an environment variable for enhanced security, but we are using one here for demo purposes.

Set up a TopicClient

This code creates the TopicClient that you will use to interact with your pub/sub topic.

CredentialProvider.fromEnvVar("MOMENTO_API_KEY"), TopicConfigurations.Laptop.latest
).use { topicClient ->

Publish a message to a topic

This is an example of publishing a message to a topic called "topic", then catching the return value to check if the publish was successful.

when (val response = topicClient.publish("test-cache", "test-topic", "test-message")) {
is TopicPublishResponse.Success -> println("Message published successfully")
is TopicPublishResponse.Error -> throw RuntimeException(
"An error occurred while attempting to publish message to topic 'test-topic': ${response.errorCode}",

Subscribe to a topic

This is an example of subscribing to a topic called "topic". When messages are published to this topic, the code here receives and prints them asynchronously.

when (val response = topicClient.subscribe("test-cache", "test-topic")) {
is TopicSubscribeResponse.Subscription -> coroutineScope {
launch {
withTimeoutOrNull(2000) {
response.collect { item ->
when (item) {
is TopicMessage.Text -> println("Received text message: ${item.value}")
is TopicMessage.Binary -> println("Received binary message: ${item.value}")
is TopicMessage.Error -> throw RuntimeException(
"An error occurred reading messages from topic 'test-topic': ${item.errorCode}", item

is TopicSubscribeResponse.Error -> throw RuntimeException(
"An error occurred while attempting to subscribe to topic 'test-topic': ${response.errorCode}", response

Running the code

You can find complete, working examples in the Kotlin SDK GitHub repo examples directory.


Beyond these basic API calls check out the API reference page for more information on the full assortment of Momento API calls.