LoginSignup
1
1

More than 5 years have passed since last update.

ActionCableのKotlinクライアントを実装してみた

Posted at

About

1年以上前にJavaのクライアントを実装していたのですが、Kotlinの勉強ついでに、Kotlin版のクライアントも実装してみました。

紹介

GitHubのリポジトリはこちらになります。

READMEの焼き直しですが、使い方を簡単に紹介します。

なお、Kotlin 1.1現在ではexperimentalな機能であるコルーチン(kotlinx.coroutines)を使っています。

Gradleによる導入

JitPack経由で、Gradleによる導入が可能です。

repositories {
    jcenter()
    maven { url "https://jitpack.io" }
}

dependencies {
    compile 'com.github.hosopy:actioncable-client-kotlin:0.0.1'
}

基本的なインターフェース

ActionCable,Channel,Subscriptionなど、基本的にはJavaScriptのインターフェースと世界観を合わせています。
onReceivedで受信するJSON(JsonObject, JsonArray)のインタフェースは、Klaxonに依存することにしました。

// 1. Setup
val uri = URI("ws://cable.example.com")
val consumer = ActionCable.createConsumer(uri)

// 2. Create subscription
val appearanceChannel = Channel("AppearanceChannel")
val subscription = consumer.subscriptions.create(appearanceChannel)

subscription.onConnected = {
    // Called when the subscription has been successfully completed
}

subscription.onRejected = {
    // Called when the subscription is rejected by the server
}

subscription.onReceived = { data: Any? ->
    // Called when the subscription receives data from the server
    // Possible types...
    when (data) {
        is Int -> { }
        is Long -> { }
        is BigInteger -> { }
        is String -> { }
        is Double -> { }
        is Boolean -> { }
        is JsonObject -> { }
        is JsonArray<*> -> { }
    }
}

subscription.onDisconnected = {
    // Called when the subscription has been closed
}

subscription.onFailed = { error ->
    // Called when the subscription encounters any error
}

// 3. Establish connection
consumer.connect()

// 4. Perform any action
subscription.perform("away")

// 5. Perform any action with params
subscription.perform("hello", mapOf("name" to "world"))

パラメータ指定

先ほどの例ではChannelにパラメータを指定していませんでしたが、パラメータを指定することもできます。

val chatChannel = Channel("ChatChannel", mapOf("room_id" to 1))

Subscription#performについても同様です。

subscription.perform("send", mapOf(
    "comment" to mapOf(
        "text" to "This is string.",
        "private" to true,
        "images" to [
            "http://example.com/image1.jpg",
            "http://example.com/image2.jpg"
        ]
    )
))

パラメータコンテナの型はMap<String, Any?>としていますが、内部ではKlaxonのJsonObjectに変換されるため、値に指定可能な型についてはKlaxonの仕様を意識する必要があります。

Option

その他、いくつかOptionがあるのですが、長くなりそうなので詳しくはREADME#Optionsを参照して下さい。

Kotlinで実装してみた所感

  • スコープ関数?が便利
  • コルーチンが便利
  • Javaのライブラリを参照しても意外と苦じゃない
  • Kotlinかわいい
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1