How to build a live commenting feature using Kotlin

Published Dec 27, 2017
How to build a live commenting feature using Kotlin

When building out applications, it’s not uncommon to have a commenting feature. With live commenting, comments added will update in realtime across all devices without the user refreshing the page. Applications like Facebook already have this feature.

In this post, we will build a basic commenting application. We will assume that the user is leaving a comment to a make-believe post. Here is a screen recording of what we will be building:



To follow along in this tutorial you will need the following requirements:

When you have all the requirements let’s start.

Create New Application on Pusher

Log into your Pusher dashboard, select apps on the left navigation bar and create a new app. Input your app name (test-app in my own case), select a cluster (eu – Ireland in my case).


When you have created the Pusher app, we will move on to creating our Kotlin application.

Creating our Android Project with Kotlin Support

Open android studio, create a new project. Insert the name of your app and Company domain name then select the “include kotlin support” checkbox to enable Kotlin in the project.


For this article, we will set the minimum supported Android version at 4.03 (API 15). Next, choose an empty activity template and click on Finish.


Getting the Client Ready

Add the pusher dependency in your app build.gradle file:

implementation 'com.pusher:pusher-java-client:1.5.0'

Our layout file will contain:

  • A recycler view (to display the comments).
  • An edit-text view (to input our message).
  • A button (to trigger an action to send a message).

A default project is created with the recycler view dependencies, however, look out for this dependency:

 implementation ''

and if you don’t find it, add it.

Here is our layout snippet:

<?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android=""

            android:layout_height="match_parent" />
                    android:layout_weight="1" />
                        android:text="Send" />

This is what our app looks like at the moment. It is very bare with no comments yet:


We then create a recycler view adapter class named RecyclerViewAdapter.kt. This adapter is a class that handles the display of items in a list.

Paste the code below into our new class:

    class RecyclerViewAdapter (private val mContext: Context) 
      :RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder>() {        

        // The initial empty list used by the adapter
        private var arrayList: ArrayList<String> = ArrayList()

        // This updates the adapter list with list from MainActivity.kt which contains the messages.  
        fun setList(arrayList: ArrayList<String>) {
            this.arrayList = arrayList

        // The layout design used for each list item
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
            val view = LayoutInflater.from(mContext).inflate(android.R.layout.simple_list_item_1, parent, false)
            return MyViewHolder(view)

        // This displays the text for each list item
        override fun onBindViewHolder(holder: RecyclerViewAdapter.MyViewHolder, position: Int) { 

        // This returns the size of the list.
        override fun getItemCount(): Int {
            return arrayList.size

        inner class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), 

        View.OnClickListener {
            var text: TextView = itemView.findViewById<View>( as 
            init {

            override fun onClick(view: View) {


We will need the Retrofit library (a “type-safe HTTP client”) to enable us send messages to our remote server which we will build later on.

After adding the retrofit dependencies, your app build.gradle file should look like this:

 apply plugin: ''
    apply plugin: 'kotlin-android'
    apply plugin: 'kotlin-android-extensions'

    android {
        compileSdkVersion 26
        defaultConfig {
            applicationId ""
            minSdkVersion 15
            targetSdkVersion 26
            versionCode 1
            versionName "1.0"
            testInstrumentationRunner ""
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), ''

    dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
        implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
        implementation ''
        implementation ''

        // pusher depencency
        implementation 'com.pusher:pusher-java-client:1.5.0'

        // retrofit dependencies
        implementation 'com.squareup.retrofit2:retrofit:2.3.0'
        implementation 'com.squareup.retrofit2:converter-scalars:2.3.0'
        implementation 'com.squareup.retrofit2:converter-gson:2.3.0'

        // testing dependencies
        testImplementation 'junit:junit:4.12'
        androidTestImplementation ''
        androidTestImplementation ''
Next, create an API Interface file in the src/main/kotlin folder called ApiService.kt. This interface is used to define endpoints to be used during network calls. For this application, we will create just one endpoint:

    interface ApiService {
        fun sendMessage(@Path("message") title: String):Call<String>
Create a Retrofit Client class in the src/main/kotlin folder called RetrofitClient.kt. This class gives us an instance of Retrofit for our network calls:

    class RetrofitClient {
        fun getClient(): ApiService {
            val httpClient = OkHttpClient.Builder()

            val builder = Retrofit.Builder()

            val retrofit = builder

            return retrofit.create(

TIP: We are using the address because this is how the Android default emulator recognises localhost. So the IP address refers to a local server running on your machine.

We now move to our MainActivity.kt file and update it with the methods below:

override fun onCreate(savedInstanceState: Bundle?) {


        // list to hold our messages
        var arrayList: ArrayList<String> = ArrayList()

        // Initialize our adapter
        val adapter = RecyclerViewAdapter(this)

        // assign a layout manager to the recycler view
        recycler_view.layoutManager = LinearLayoutManager(this)

        // assign adapter to the recycler view
        recycler_view.adapter = adapter

        // Initialize Pusher
        val options = PusherOptions()
        val pusher = Pusher("PUSHER_APP_KEY", options)

        // Subscribe to a Pusher channel
        val channel = pusher.subscribe("my-channel")

        // this listener recieves any new message from the server
        channel.bind("my-event") { channelName, eventName, data ->
            val jsonObject = JSONObject(data)
            runOnUiThread { adapter.setList(arrayList) }

        // We check for button clicks and if any text was inputed, we send the message
        button_send.setOnClickListener(View.OnClickListener {
            if (edit_text.text.length>0) {

    } // end of onCreate method

    fun sendMessage(message:String) {
        val call = RetrofitClient().getClient().sendMessage(message)

        call.enqueue(object : Callback<String> {
            override fun onResponse(call: Call<String>, response: Response<String>) {
            override fun onFailure(call: Call<String>, t: Throwable) {

    } // end of sendMessage method

    fun hideKeyboard(activity: Activity) {
        val imm = activity.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager

        // Find the currently focused view, so we can grab the correct window token from it.
        var view = activity.currentFocus

        // If no view currently has focus, create a new one, just so we can grab a window token from it
        if (view == null) {
            view = View(activity)

        imm.hideSoftInputFromWindow(view.windowToken, 0)
    } // end of hideKeybnoard method

NOTE: You will need to replace the PUSHER_APP_* keys with the credentials found in your Pusher application dashboard.

In the onCreate method, we initialised the list to hold the messages, the recycler view adapter to handle the display of items on the list, and assigned the recycler view accordingly.

We then initialised PusherOptions and Pusher objects with the necessary parameters. Remember to set the Pusher objects first parameter with your own app key. Your app keys can be found on the App Keys tab of the app you created. If you have forgotten the cluster you chose when creating the app, you can also find it there.

Next, we create a listener for events on that channel. When a new message is received, it will be added to our list and the updated list will be assigned to our adapter so that it can be displayed immediately.

Finally, we added a listener to the button in our layout to enable us send messages. After messages are successfully sent, we clear the text and hide the keyboard.

Next up is to add the Internet permission in your AndroidManifest.xml file. Update the file with the code snippet below:

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

With this change, we are done building our client application.

Building our Kotlin Back-end Server

Our server will be built with Kotlin and hosted locally. You can follow the steps below to quickly get your server running.

Create a new Gradle based Kotlin project in IntelliJ IDEA.


Enter a “groupId” for your app. A groupId can be a package name and it’s usually something like “com.example”.

Next, enter an “artifactId”, it’s usually something like “pusher-server”


In our project build.gradle file, we will add Ktor and pusher server dependencies. Ktor is a framework for building servers and clients in connected systems using the Kotlin programming language.

Here is our complete build.gradle file which includes all the dependencies we need:

group 'com.example'
    version '1.0-SNAPSHOT'

    buildscript {
        // dependency version variables
        ext.kotlin_version = '1.1.4-3'
        ext.ktor_version = '0.2.4'
        repositories {
        dependencies {
            classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

    apply plugin: 'application'
    apply plugin: 'kotlin'

    sourceCompatibility = 1.8

    repositories {
        maven {
            url ''
        maven {
            url ''

    mainClassName = 'org.jetbrains.ktor.jetty.DevelopmentHost'

    dependencies {
        compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version"
        // ktor dependencies
        compile "org.jetbrains.ktor:ktor-core:$ktor_version"
        compile "org.jetbrains.ktor:ktor-locations:$ktor_version"
        runtime "org.jetbrains.ktor:ktor-jetty:$ktor_version"
        // pusher server dependency
        compile "com.pusher:pusher-http-java:1.0.0"
        testCompile group: 'junit', name: 'junit', version: '4.12'

    compileKotlin {
        kotlinOptions.jvmTarget = "1.8"

    compileTestKotlin {
        kotlinOptions.jvmTarget = "1.8"

In your `src/main/kotlin` folder, create a `Main.kt` file and insert this snippet:

``` language-java
    fun Application.main() {

        val pusher = Pusher("PUSHER_APP_ID", "PUSHER_APP_KEY", "PUSHER_APP_SECRET")

        install(Routing) {
            get("/{message}") {
                val i = call.parameters["message"]!!
                pusher.trigger("my-channel", "my-event", Collections.singletonMap("message", i))
                call.respond("response sent")


NOTE: You will need to replace the PUSHER_APP_* keys with the credentials found in your Pusher application dashboard.

In the above snippet, we have defined a route that handles new messages. When a message is received, it sends the message to the Pusher channel so it can be picked up by any event listeners on the same channel.

Next, open the src/main/resources/application.conf file and set the port to 5000. If the file does not exist, create it and insert this snippet:

ktor {
        deployment {
            environment = development
            port = 5000

        application {
            modules = [com.example.MainKt.main]

This file allows you configure the server parameters.

After that, open the Terminal on the IDE, and type ./gradlew run to run the server. To test your server, open http://localhost:5000/message and you should see a display saying “response sent”.

Now we’re done with everything. We can make comments and receive updates with no stress, thanks to Pusher.

How-to-build-live-commenting-in-Kotlin-7 (1).gif


In this article, we have demonstrated how to work with Pusher and Kotlin while creating the commenting system. It is a very simple implementation and, of course, you can do more. I am curious to see what you will come up with.

If you have a question or feedback, leave them below in the comment section. The source code for the application is available on GitHub.

This blog post first appeared on the Pusher Blog

Discover and read more posts from Neo Ighodaro
get started