Welcome, Kotlin!

Google recently made Kotlin an official application development language for Android. We are very excited to announce that the new version of the Lightstreamer client API for Android embraces Kotlin. By ensuring full support for both Kotlin and Java, the library enables developers to choose their favorite programming language or even mix them.

Why Kotlin?

JetBrains started to develop Kotlin six years ago for their own use. They aimed at creating a language with less issues than Java and greater performance than Scala. The result of this effort is a 100% JVM compatible language, easy to learn and safe to use even in production. 

Kotlin has a strong type system without raw types. It offers proper function types, lambda expressions, inline functions, first-class delegation, operator overloading, and coroutines. Moreover, Kotlin separates the interfaces of read-only collections and mutable collections.

Many frameworks announced their support for the Kotlin language, including Spring, Gradle, and Vert.x. Kotlin persuaded even big companies, including Netflix, Trello, Pinterest, Basecamp, Square and Corda.

At Google I/O 2017, Google announced Kotlin as an official programming language for Android development, making it a “first-class” language. Kotlin might become the next big thing in the JVM world.

Lightstreamer and Kotlin

Version 3.1.3 of Lightstreamer’s Android client library has been released and is publicly available on Maven.
Upgrading to version 3.1.3 brings enhanced support for type safety, reduces app crashes, and speeds up the development process by checking some Java common mistakes directly when typing the code. To reach this result, Lightstreamer chose to address Java’s “million dollar mistake” directly into its codebase, by adding support for JSR-305 annotations. Many Java checking frameworks take advantage of annotated code, which works out of the box and in many cases does not require any modification to your build process.
Modern Java IDEs automatically check variable nullability and they show some code vulnerability directly into the editor. You can configure your IDE to raise an error if any null checking fails. This ensure 100% safety, avoiding Java NullPointerException.
Kotlin has native support to JSR-305 and it encloses all of these checks directly into its type system. All Java non-primitive variables are nullable, while Kotlin variables can be either nullable or not-nullable, so that the compiler is able to ensure null safety at compile time. After upgrading to version 3.1.3 or greater of the Android client library for Lightstreamer, Kotlin integration and null safety are guaranteed with no additional effort.

Demo Time

Let’s write a simple Kotlin Android app using the new client library and a demo Lightstreamer server. We will use Android Studio with the Kotlin plugin installed (Android Studio 2 requires manual plugin installation).
Pay attention: the following code is only for demonstration purpose, make sure to optimize and customize it for your specific use case.

You can find the full source code and project resources for this demo on GitHub.
Lightstreamer supports a wide range of tuning options; fortunately, you can fine tune them on the server-side, so, to instantiate a connection you require only the server URL. In this case we use the public demo server “http://push.lightstreamer.com/” and we save it in strings.xml.
Let’s define a ClientProxy inside the StockListDemoApplication. This instance shares a Lightstreamer connection to the “DEMO” adapter set across the entire application, making it easy to reuse all the established resources.

private val lsClient = LightstreamerClient(
        resources.getString(R.string.host),
        "DEMO")
        .apply {
            connect()
        }

ClientProxy adds to LightstreamerClient some useful methods to start and stop the Lightstreamer connection, so it is possible to save bandwidth when the app is idle.
The client library automatically applies the best effort to ensure a reliable data connection for any Android device, thus solving proxy/firewall issues and connection drops. So, we will focus on the next step: requesting data to the server.
To subscribe to real-time data on a Lightstreamer Server you need to specify the data adapter name (QUOTE_ADAPTER), the subscription mode (MERGE), the item names (item1..item20) and the field names (stock_name, last_price, timestamp). By using these information, StocksFragment defines a main subscription and attaches two listeners on that.

private val mainSubscription = Subscription("MERGE", items, subscriptionFields).apply {
    dataAdapter = "QUOTE_ADAPTER"
    requestedMaxFrequency = "1"
    requestedSnapshot = "yes"
    addListener(LogSubscriptionListener)
    addListener(mainSubscriptionListener)
}

The first one is the LogSubscriptionListener object, which logs every client event, making it easy to debug any subscription problem. I suggest you to grab and adapt it for testing purpose.

The second one is MainSubscription. For each item update, this listener dispatches the event to the StockForList target. This delegates EmptySubscriptionListener for every unmanaged notification, so the code is pretty tiny.

class MainSubscription(private val list: List<StockForList>) :
        SubscriptionListener by EmptySubscriptionListener {

    var context: Context by Delegates.notNull()

    override fun onItemUpdate(update: ItemUpdate) {
        val toUpdate = list[update.itemPos - 1]
        toUpdate.update(update, this.context)
    }
}

Finally, StockForList is responsible to show the correct data in a nice interface. It implements the “update” method, which refreshes data in the list and applies some color to highlighthot values.

Let’s make a quick step-by-step recap:

  1. Configure Lightstreamer client dependency in your build.gradle
  2. Create Lightstreamer client using the server endpoint URL
  3. Depending the current app view, subscribe to the right Lightstreamer item using the appropriate item name, item mode, and field names
  4. Register your subscription listener and show the live data

Starting from the current version, you are free to write your Android apps using plain Java or new Kotlin. Both are well integrated and fully supported.

Let us know your feedback and happy Kotlin coding!

September 13, 2024
Originally published: July 19, 2017


4 min read

Table of Contents