🎉 New! Integrate Beams with Chatkit for powerful push notifications—find out more

Extensible API for in-app chat


Build scalable realtime features


Programmatic push notifications



Read the docs to learn how to use our products


Explore our tutorials to build apps with Pusher products


Reach out to our support team for help and advice

Sign in
Sign up

Build a realtime counter using Kotlin

  • Perfect Makanju

November 9th, 2017
A basic understanding of Kotlin is needed to follow this tutorial.

It is important to show realtime updates of what is happening in an application, and one form of this is a realtime counter. A realtime counter can be used to show users of an app how other users are interacting with their content. For example, Instagram uses a realtime counter to show when viewers like a live video. This makes users of the application feel more engaged as they will be getting immediate feedback when things change.

In this tutorial, I’ll show you how to use Pusher to create a realtime counter in Kotlin. We will be creating a simple Android application with a counter showing how many users have clicked on a button. This click count also updates in realtime when other users click on it. Below is a GIF of how the application will work:

We will be using Kotlin to develop both the realtime web server and the Android application, so a basic working knowledge of Kotlin and Android development will be required to follow this tutorial.


We will build a web server that keeps track of how many times a button has been clicked. The web server will also expose an endpoint which the Android application can call to send click events, the web server would then increment the click count and send a broadcast using Pusher to all clients currently subscribed to the click event.

So based on the above, this post is going to be in two sections:

  1. Building the realtime server using Kotlin
  2. Building the Android application using Kotlin

So lets get started.

Create a Pusher account

Before we get started, you would need to create a Pusher application. Go on to Pusher and create an account, but if you already have an account, just login. Then, create a new app from the dashboard and store the apps keys as we would be using them later in this post.

Building the realtime server

Kotlin is a very versatile language and one of its interesting features is its ability to be compiled to Javascript. We are going to use this feature to build a Kotlin server application that would be run with Node.js.

In order to compile Kotlin to Javascript and run on Node.js, you would need to have Node.js and Gradle installed on your computer. The remaining part of this tutorial will assume you have both installed on your machine.

First, run the command:

    npm init

After entering the appropriate setup information, you should have your package.json file created for you in your directory. Next, create a build.gradle file in the same directory and copy the following into the file:

    group 'kotlin-realtime-counter'
    version '1.0'
    buildscript {
      ext.kotlin_version = '1.1.3'
        repositories {
      dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    apply plugin: 'kotlin2js'
    repositories {
    dependencies {
      compile "org.jetbrains.kotlin:kotlin-stdlib-js:$kotlin_version"
    compileKotlin2Js.kotlinOptions {
      moduleKind = "commonjs"
      outputFile = "build/app.js"

This build.gradle file would compile our Kotlin code into Javascript to run. Some things to note are:

  1. You can change the group and version to something that suits your project. In this case it is set to kotlin-realtime-counter.
  2. The outputFile option at the bottom of the file is used to set where the location of the Javascript file that our Kotlin code will be compiled into. In this case it would be compiled into the build directory inside an app.js file.

Now in order for this build to work, all the Kotlin code needs to be put in the directory src/main/kotlin. This can be created with the following command:

    mkdir -p src/main/kotlin

After executing the above command, your project directory structure should look like this:

    |- src
      |- main
        |- kotlin
    |- build.gradle
    |- package.json

So, let’s get down to coding our server. We need to install the following Node.js libraries using npm:

    npm install --save kotlin express pusher

This will install the Kotlin.js library needed for our compiled Javascript code to work. It will also be installing express for creating our server and the Pusher library for making realtime event broadcasts.

Now, create a file named ClickCount.kt inside the src/main/kotlin folder, and write the following code in it:

    data class ClickCount(val count: Int)

This ClickCount class will be used as a data object to encapsulate information about the number of times a click has be recorded. It’s importance will be seen later in the post.

Next, create a file named App.kt inside the src/main/kotlin folder. In the App.kt file, we need to first define some external functions and classes that would exist normally in the Node.js environment. This way, Kotlin would know the signature of these functions and not throw an error when they are being used.

    external fun require(module: String): dynamic

    external class Pusher(config: Any) {
        fun trigger(channel: String, event: String, data: Any)

Here we define the following functions:

  • require(): This is declaring the standard nodejs require function used to import modules. We will be using it later to import the express library. The [dynamic](https://kotlinlang.org/docs/reference/dynamic-type.html) type only exists for Kotlin codes targeting Javascript. The most peculiar feature of dynamic is that we are allowed to call any property or function with any parameters on it, hence giving us the dynamic typed feature of Javascript.
  • Pusher: Here we are declaring the Pusher class and the Pusher.trigger() function we will be using later on. The [@JsModule](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.js/-js-module/index.html) indicates that this class should be imported from the pusher library we added as a dependency earlier.

External functions and class declarations are generally used to declare functions or objects that exists on the Javascript global object.

External class declarations having the @JsModule are typically used to declare classes of external modules that need to be instantiated using the new keyword, as Kotlin doesn’t support the new keyword.

Next, we initialize our server and Pusher configuration values.

    val express = require("express")
    val pusherConfig  = object {
        val appId = "YOUR_PUSHER_APP_ID"
        val key = "YOUR_PUSHER_KEY"
        val secret = "YOUR_PUSHER_SECRET"
        val cluster = "YOUR_PUSHER_APP_CLUSTER"
        val encrypted = true
    val clickChannel = "click-channel"
    val clickEvent = "click-event"
    var currentClickCount = 0

You would need to update your pusherConfig object values with the keys you got from creating a Pusher application earlier. The currentClickCount variable will be used to keep track of the number of times a click has been recorded.

Next, we implement the main function that would be run when our code is executed.

    fun main(args: Array<String>) {
        val app = express()
        val pusher = Pusher(pusherConfig)

        app.get("/counts", { _, res ->
        app.post("/clicks", { _, res ->
            // broadcast new ClickCount
            pusher.trigger(clickChannel, clickEvent, ClickCount(currentClickCount))

        app.listen(9999, {
            println("Listening on port 9999")

Here we initialize the express server and create a pusher object using the pusherConfig declared earlier. We then expose two endpoints:

  1. GET /counts: HTTP GET requests will be sent to this endpoint to get the current click counts recorded so far. The currentClickCount is then returned as a JSON object of ClickCount.
  2. POST /clicks: POST requests will be made to this endpoint to indicate that the button has been clicked. This will record the click count by incrementing the currentClickCount and then send a broadcast of the updated currentClickCount using pusher to all listeners of the clickEvent on the clickChannel.

And lastly in the main() function, we expose the express server to listen on port 9999.

Now the server code is ready and we just need to compile to Javascript so we can run with node. To build, run the following Gradle command in the same directory containing the build.gradle file created earlier:

    gradle build

On completion, this would generate a Javascript file in build/app.js. We just need to run this file using node like this:

    node build/app.js

And voila 👏, you should have the realtime server now running on port 9999. The whole code for this server can be found in this repository.

Now, let’s go on to build the Android application that would be interacting with this server.

2. Building the Android application

To make it easy to get started with Kotlin for Android development, we will be using Android Studio 3.0 as this version has the Kotlin plugin bundled with it. If you are using an Android Studio version less than than 3.0 refer here for detailed instructions to get started.

So launch your Android Studio 3.0 IDE and create a new project. You can give the project any name but for this tutorial we will name the project ‘Click Counter’. Also ensure that you check the Include Kotlin Support option as shown in the image below:

Click on Next several times and then Finish and the Android project will be created and setup.

After the project has finished building, open up your app module’s build.gradle file and add the following to the dependencies section:

    apply plugin: 'com.android.application'
    apply plugin: 'kotlin-android'
    apply plugin: 'kotlin-android-extensions'

    android {

    dependencies {
      implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"

      implementation 'com.pusher:pusher-java-client:1.5.0'
      implementation 'com.squareup.okhttp3:okhttp:3.8.0'
      implementation 'com.google.code.gson:gson:2.8.0'

If you are using an Android Studio version earlier than 3.0, you should replace implementation with compile. implementation was introduced with Gradle 3.0 and compile is now being deprecated. You can read more about these changes here.

Also ensure the applied ‘kotlin-android-extensions’ plugin is added to the build.gradle file if you are using an Android Studio version earlier than 3.0

Next, open up your AndroidManifest.xml file and add the Internet permission like so:

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"

        <uses-permission android:name="android.permission.INTERNET"/>



Next, let us design the interface of our application. The application would have a single activity which contains a single button and text view showing the current number of times the button has been clicked. So open your activity_main.xml layout file and update it with the following code:

    <?xml version="1.0" encoding="utf-8"?>

                android:text="Click to show some love"
                app:layout_constraintTop_toTopOf="parent" />


                android:text="Number of clicks so far is:"
                app:layout_constraintTop_toBottomOf="@+id/clickButton" />

                app:layout_constraintTop_toBottomOf="@+id/textView" />

The layout is pretty straight forward, things to note are the FloatingActionButton with id clickButton and the countTextView to display the current click count.

Now, create a new Kotlin class named ClickCount inside the com.pusher.clickcounter and copy the following into the file:

    package pusher.com.clickcounter

    data class ClickCount(val count: Int)

Next, open the MainActivity.kt class and lets write the code that ties all the functionality together. Inside this file, start by defining some configuration constants and initializing some required variables.

    package com.pusher.clickcounter


    class MainActivity : AppCompatActivity() {
      companion object {
          const val SERVER_URL = "http://NODE_JS_SERVER_ENDPOINT"
          const val PUSHER_API_KEY = "PUSHER_API_KEY"
          const val CLICK_CHANNEL = "click-channel"
          const val CLICK_EVENT = "click-event"

      val pusherOptions = PusherOptions().setCluster(PUSHER_CLUSTER)
      val pusher = Pusher(PUSHER_API_KEY, pusherOptions)
      val httpClient = OkHttpClient()


Note that you would have to set the SERVER_URL to the actual url where your realtime server is running. Also, update the PUSHER_API_KEY and PUSHER_CLUSTER values to your Pusher applications credentials.

Next, the onCreate() method should look like this:

    package com.pusher.clickcounter

    import kotlinx.android.synthetic.main.activity_main.*

    class MainActivity : AppCompatActivity() {

      override fun onCreate(savedInstanceState: Bundle?) {

          clickButton.setOnClickListener { postClick() }


First, we fetch the current click count by invoking the fetchCurrentClickCount() method. Next, we connect to get realtime updates of when the click count changes. Finally we attach an onClickListener to the clickButton button.

We are able to get a reference to the clickButton button directly without having to use findViewById() because of the Kotlin Android Extensions plugin we applied to this project in the build.gradle file.

Now let us explore the contents of the fetchCurrentClickCount(), connectToRealtimeUpdates() and postClick() functions respectively.

The fetchCurrentClickCount() method

This method makes a GET request to the servers /counts endpoint and updates the countTextView's text with the count gotten from the servers response.

    private fun fetchCurrentClickCount() {
      val getClickCountRequest = Request.Builder().url("$SERVER_URL/counts").build()

        .enqueue(object: Callback {
          override fun onResponse(call: Call?, response: Response?) {
            response?.body()?.also { body ->
              val clickCount = Gson().fromJson(body.string(), ClickCount::class.java)
              runOnUiThread { countTextView.text = clickCount.count.toString() }

          override fun onFailure(call: Call?, e: IOException?) {
            runOnUiThread {
              showError("Network error loading current count", "Retry") {

If an error occurs while making the request, an error message will be displayed using the showError() function:

    private fun showError(msg: String, action: String, callback: Snackbar.(View) -> Unit) {
        val errorSnackbar = Snackbar.make(rootLayout, msg, Snackbar.LENGTH_INDEFINITE)
        errorSnackbar.setAction(action) {
            callback(errorSnackbar, it)

The showError() function displays a Snackbar containing the msg passed in and an action button. When the action button is clicked, the callback is invoked.

Notice the type of the callback function is an extension function on Snackbar ( i.e. Snackbar.(View) → Unit ). This makes it easy for the calling code to have access the Snackbar instance without explicitly passing a reference to the callback.

The connectToRealtimeUpdates() method

The connectToRealtimeUpdates() method subscribes to the Pusher CLICK_CHANNEL and binds an event listener to CLICK_EVENT' events on the channel.

    private fun connectToRealtimeUpdates() {
      val pusherChannel = pusher.subscribe(CLICK_CHANNEL)
      pusherChannel.bind(CLICK_EVENT) { _, _, data ->
        val clickCount = Gson().fromJson(data, ClickCount::class.java)
        runOnUiThread { countTextView.text = clickCount.count.toString() }

The event listener deserializes the data into a ClickCount object using Gson and then updates the countTextView's text with the count provided.

The postClick() method

The postClick() method is invoked when the clickButton is tapped. It sends a POST request to the servers /clicks endpoint.

    private fun postClick() {
      val emptyBody = RequestBody.create(null, "")
      val postClickRequest = Request.Builder().url("$SERVER_URL/clicks").post(emptyBody)

        .enqueue(object: Callback {
          override fun onResponse(call: Call?, response: Response?) { }

          override fun onFailure(call: Call?, e: IOException?) {
            runOnUiThread {
                showError("Network error sending click","Retry") {

If an error occurs while posting the click event, a error Snackbar is displayed via the showError() function.

And finally, in the activity we connect and disconnect pusher in the onResume() and onPause() lifecycle methods respectively.

    class MainActivity : AppCompatActivity() {

      override fun onResume() {

      override fun onPause() {

There you have it. The realtime counter Android application is now ready. You can find the complete code for the Android application here.

Testing it out

To test it out, ensure that the realtime server we built earlier is running and the Android application’s SERVER_URL is updated accordingly.

Now, run the application on multiple devices. You would notice that as you click on the button, the count increases in realtime across all the devices.


It has been a long post, but we were able to see how Pusher can be used to build a realtime counter. We have also seen how we can use Kotlin’s super powers to supercharge our application.

Some additional things that can be done to improve this application include:

  • Sharing similar Kotlin code between the server and Android application. For example, the ClickCount class can be moved out to a separate module and shared between the server and Android applications. Link to a sample project that achieved this can be found below.
  • Changing the data type for the counter from Int to something like BigInteger to handle larger counts.
  • Persisting the currentClickCount to a database. Note that this may give rise to some other issues that need consideration such as atomically incrementing the click count to avoid race conditions.

Let me know in the comments below if you have any questions or suggestions to improve this tutorial. I’ll love to hear your thoughts. Cheers!

Further Reading

Clone the project repository
  • Kotlin
  • Android
  • Social
  • Live Counter
  • Channels


  • Channels
  • Chatkit
  • Beams

© 2020 Pusher Ltd. All rights reserved.

Pusher Limited is a company registered in England and Wales (No. 07489873) whose registered office is at 160 Old Street, London, EC1V 9BW.